I am new to webpack and worked out almost all build sections, but now the problem is that I want to pass the environment variables from a .env file to webpack config, so tha
It doesn't match your case exactly (although partially), but I've found this formula to be working best for me.
I use a combination of 2 libs: dotenv to read the .env
file for the webpack.config.js
(configuration) needs, and webpack-dotenv-plugin for the validation (based on .env.example
file) and to pass all the vars from .env file to the application code:
Part of my webpack.config.js
:
// this is to load env vars for this config
require('dotenv').config({ // it puts the content to the "process.env" var. System vars are taking precedence
path: '.env.webpack',
});
// and this to pass env vars to the JS application
const DotenvPlugin = require('webpack-dotenv-plugin');
plugins section:
plugins: [
// ...
new DotenvPlugin({ // makes vars available to the application js code
path: '.env.webpack',
sample: '.env.webpack.example',
allowEmptyValues: true,
}),
// ...
]