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 that I can pass that variables to my build files via webpack.DefinePlugin
plugin.
Currently I am able to to pass environment variable directly from webpack to to my build. Please see the code below which I used in webpack.
new webpack.DefinePlugin({ "API_URL": JSON.stringify("http://my-api.com"), "FRONT_END_API_KEY" : "MYFRONTENDKEYGOESHERE" }),
My package.json
build script is
"scripts": { "start": "NODE_ENV=development webpack-dev-server --progress --port 8000 --content-base app/build/src" }
The . env file contains the individual user environment variables that override the variables set in the /etc/environment file. You can customize your environment variables as desired by modifying your . env file.
In case you are still wondering what all this means, well, you are probably new to the . env file. It's actually a simple configuration text file that is used to define some variables you want to pass into your application's environment. This file needs a something like a parser to make it work.
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); }),
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) }) ] ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With