首页 > 解决方案 > 如何在 nativescript 中访问 webpack 环境变量?

问题描述

我想在 webpack.config.js 中存储一个环境变量,当我在 Nativescript 中将应用程序与 webpack 捆绑时设置。目标是即使在捆绑之后也对环境变量保密。

我怎么做?

我相信这应该是可能的,如下所述(但未详细说明):https ://docs.nativescript.org/performance-optimizations/bundling-with-webpack ://docs.nativescript.org/performance-optimizations/bundling-with-webpack 。

但我无法让它在测试中工作。我是 webpack 的新手,所以我可能会遗漏一些明显的东西。

为了简单起见,我将调用变量“simple_env_variable”,并给它一个值“here_is_the_value!”。

要访问这个变量,我想我会用:

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

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

例如:

webpack.config.js:

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

酷组件.ts:

export class CoolComponent {

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

标签: angularwebpacknativescript

解决方案


以 Nick Lliev 的回答为起点,从这里的讨论中,升级我的 webpack 和 nativescript 设置后,以下内容对我有用:

webpack.config.js:

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

主页.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 运行命令:

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

推荐阅读