Reputation: 96
I am trying to utilise the process.env.NODE_ENV to switch between the environments for my react native app, and am facing two issues here
1. Assigning parameter to NODE_ENV doesn't seem to change the env value straight forward,
executing the below command shows that it changed process.env.NODE_ENV value but doesnt seem to have changed the global.process.env.NODE_ENV
execution command:
NODE_ENV=development npm start -- --reset-cache
output: Please note, the second log statement still prints out development.
console.log("printing the changed value - ", process.env.NODE_ENV); // --> printing the changed value - production
console.log("checking the env content - ", process.env); // ---> checking the env content - { NODE_ENV: 'development' }
Workaround that i tried is to assign the process.env.NODE_ENV to the global instance,
global.process.env.NODE_ENV = process.env.NODE_ENV
Please do advise if this is a good approach to proceed with.
2. Assigning "Production" as a value to NODE_ENV throws Attempted to Assign to read only property error,
Execution Command:
NODE_ENV=production npm start -- --reset-cache
Please find image attached - AssignToReadOnlyPropertyIssue
Upvotes: 0
Views: 2542
Reputation: 2085
The problem your facing here comes from an erroneous assumption:
react-native
doesn't execute javascript in the same way as node.
Let's consider the following npm script:
"scripts": {
"start": "node index.js"
}
When running SOME_VAR="some value" npm start
, process.env
will contain a entry for that environment variable, since it is running from the process where SOME_VAR
was defined.
In react-native
something different happens:
calling npm start
starts the react-native packager which bundles your javascript code and then sends that javascript bundle to the installation in your emulator or device, where the bundle is in its turn executed. react-native
's packager doesn't "forward" the environment variables defined where the javascript was bundled.
Hopefully there are packages that aid us to be able to keep using the same patterns we're used to using when developing node apps.
One I found really helpful was babel-plugin-transform-inline-environment-variables
. This is a babel plugin that transforms process.env.SOME_VAR
type calls to the value of SOME_VAR
during bundle time.
The only headache I had with it was that when I was first trying to see how it worked I was changing the environment variables, but it only seemed to work "randomly". Turns out I was a victim of webpack
's cache. If there are no changes in the code it is watching it won't update the bundle. I then learned I had to be aware of that
Upvotes: 2