Reputation: 1205
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? **/
Upvotes: 3
Views: 2087
Reputation: 1205
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"
Upvotes: 3
Reputation: 9670
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
}
Upvotes: 3