Passing NODE_ENV environment variable from Webpack to code
Hello everybody,
I wrote this article with a very specific title since it’s a common practice for different use cases. I thought a lot of people would find this answer while looking for a method to pass a NODE_ENV variable exposed in the npm script
of the package.json directly to the code.
Let’s first review the stack. We have two different environments development
and production
.
We run them through npm scripts in our package.json:
package.json
{
"name": "myApp",
"version": "1.0.0",
"description": "A javascript application",
"scripts": {
"dev": "NODE_ENV=development npm run watch",
"watch": "node ./node_modules/webpack/bin/webpack --watch --progress --profile --colors --display-error-details --display-cached",
"build": "NODE_ENV=development node ./node_modules/webpack/bin/webpack --progress --profile --colors --display-error-details --display-cached",
"build:prod": "node ./node_modules/webpack/bin/webpack --progress --profile --colors --display-error-details --display-cached --optimize-occurence-order --optimize-minimize --optimize-dedupe",
"start": "npm run watch"
}
}
This package.json expose 4 scripts + start. dev
and build
propose two development environment situations meanwhile watch
and build:prod
are meant for production testing and deployment.
We know that we can make us of them in our webpack.json reading the value of the node variable process.env
on process.env.NODE_ENV
.
In order to pass this variable to our code we need to provide it as a webpack plugin.
webpack.config.js
module.exports = {
// your config
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'production') // default value if not specified
}
})
}
NOTE: We use JSON.stringify
as a good practice to avoid different issues (security, mistakes, etc).
Now we are ready to read this variable on our code simply using:
index.js
const nodeEnv = process.env.NODE_ENV;
Of course we can decide to pass the whole process.env
variable.
Have a good day folks ๐
JavaScript making a website different lot of url create generate my past experience is not good about JavaScript website development
Hmm, not sure what to say about that
Thanks, just what I was looking for. ๐