How to access webpack environmental variables in nativescript?

与世无争的帅哥 提交于 2019-12-22 10:04:04

问题


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.

How do I do that?

I believe this should be possible, as described (but not detailed) here: https://docs.nativescript.org/performance-optimizations/bundling-with-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.

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!

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

For example:

webpack.config.js:

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

cool-component.ts:

export class CoolComponent {

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

回答1:


You can directly access the key-value pair in your code but if you are using TypeScript you should cast it to any (as TS needs strong typing for all variables).

For example

webpack.config.js

new webpack.DefinePlugin({
                "global.TNS_WEBPACK": "true",
                "process": undefined,
                "myGlobal.MyScarySecret": JSON.stringify("my big old secret")
            }),

and then in your bundled application

main-page.ts

declare let myGlobal: any;

export function navigatingTo(args: EventData) {
    let page = <Page>args.object;

    console.log(myGlobal.MyScarySecret); // my big old secret
}



回答2:


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:

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

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
}

Then the working tns run command:

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


来源:https://stackoverflow.com/questions/51975388/how-to-access-webpack-environmental-variables-in-nativescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!