How to access webpack environmental variables in nativescript?

戏子无情 提交于 2019-12-05 22:24:36

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
}

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