How to pass .env file variables to webpack config?
You can use dotenv package for this purpose.
After installing the package, add this in the top of your config:
const webpack = require('webpack'); // only add this if you don't have yet// replace accordingly './.env' with the path of your .env file require('dotenv').config({ path: './.env' });
then in plugins
section, add this:
new webpack.DefinePlugin({ "process.env": JSON.stringify(process.env);}),
webpack + dotenv
I did get inspiration from the accepted answer, but it doesn't work for me. Maybe the API of dotenv has changed.
The following works for me
import dotenv from 'dotenv'import { DefinePlugin } from 'webpack'...plugins: [ new DefinePlugin({ 'process.env': JSON.stringify(dotenv.config().parsed) })]...
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 configrequire('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 applicationconst 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, }), // ...]