如何在nativescript中访问webpack环境变量? [英] How to access webpack environmental variables in nativescript?

查看:136
本文介绍了如何在nativescript中访问webpack环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将环境变量存储在webpack.config.js中,当我将应用程序与Nativepack中的webpack捆绑在一起时,将设置该变量.目标是即使在捆绑销售之后也要保持环境变量的机密.

I want to store an environmental variable in webpack.config.js, that I will set when I bundle the app with webpack in Nativescript. The goal is to keep the environmental variable secret even after the bundle.

我该怎么做?

我认为这应该可行,如此处所述(但不详细介绍): https://docs.nativescript.org/performance-optimizations/bundling-with-webpack .

I believe this should be possible, as described (but not detailed) here: https://docs.nativescript.org/performance-optimizations/bundling-with-webpack.

但是我无法在测试中使用它.我是webpack的新手,所以我可能缺少明显的东西.

But I am not able to get it to work in testing. I am new to webpack, so I may be missing something obvious.

为简单起见,我将调用变量"simple_env_variable",并为其赋予值"here_is_the_value!".

To keep it simple, I am going to call the variable 'simple_env_variable', and give it a value 'here_is_the_value!'.

要访问此变量,我以为可以用以下方式调用它:

To access this variable, I had thought I would call it with:

$ tns build ios --bundle --env.development --env.simple_env_variable=here_is_the_value!

我要在webpack.config.js中输入什么代码,然后在ts组件中输入什么代码来访问它?

What code do I enter in webpack.config.js, and then what code do I enter in my ts component to access it?

例如:

webpack.config.js:

webpack.config.js:

module.exports = env => {
...
  const config = {
  ...
   plugins: [
   ...
     new webpack.DefinePlugin({
      "simple_env_variable": /**What Do I Enter Here***/

cool-component.ts:

cool-component.ts:

export class CoolComponent {

public myVariable = /**What Do I enter here to access the variable in webpack.config.js? **/

推荐答案

使用Nick Lliev的答案作为起点,并从讨论中

Using Nick Lliev's answer as a starting point, and from the discussion here, the following worked for me after upgrading my webpack and nativescript settings:

webpack.config.js:

webpack.config.js:

new webpack.DefinePlugin({
        "global.TNS_WEBPACK": "true",
        "process": undefined,
        "myGlobal.MySecret": JSON.stringify(env.first_property)
}),

main-page.ts:

main-page.ts:

import {OnInit...

declare let myGlobal: any

@Component...

export class MainPageComponent implements OnInit {
...

ngOnInit(): void {
  console.log(myGlobal.MySecret) // prints "yaySecret" with the run command I have below
}

然后运行tns运行命令:

Then the working tns run command:

$ tns run ios --bundle --env.uglify --env.aot --env.first_property="yaySecret"

这篇关于如何在nativescript中访问webpack环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆