How To Access Env Vars From Webpack.config.js File?
I try to access env vars from webpack.config.js through process.env.env_name, although i've access to env vars in my .env (locally) through process.env.env_name in webpack.config.
Solution 1:
Option 1 - Variables on webpack file
You can pass in your env variables on the script:
webpack --env.MY_VARIABLE=VALUE --env.MY_OTHER_VARIABLE=OTHER_VALUE
and access it:
...
module.exports = env => {
// Use env.<YOUR VARIABLE> here:console.log('MY_VARIABLE: ', env.MY_VARIABLE); // 'VALUE'
...
};
Option 2 - Variables on your app
Or you can read it from your env file using some package, like dotenv.
run npm i dotenv
.
Import it on your webpack.config.js file:
// if .env is on same folder as webpack.config.jsvar dotenv = require('dotenv')
// if is located elsewherevar dotenv = require('dotenv').config({ path: '/full/custom/path/to/your/env/vars' });
// same as above, but with abstractionvar dotenv = require('dotenv').config({path: __dirname + '/.env'});
And finally:
// define a new plugin on your webpack
plugins: [
...
new webpack.DefinePlugin({
// try:
"process.env": dotenv.parsed
// or:
'process.env': JSON.stringify(dotenv.config().parsed)
}),
]
Now you can read your variables inside your app as process.env.MY_VARIABLE
, defined in .env
.
Solution 2:
You can use webpack.DefinePlugin like this
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development'),
'BASE_URL': JSON.stringify('http://localhost:5000/')
}
})
],
Then read in your js code like this
process.env.BASE_URL
Post a Comment for "How To Access Env Vars From Webpack.config.js File?"