How to pass .env file variables to webpack config?

倾然丶 夕夏残阳落幕 提交于 2019-11-29 06:15:10
Rameez Rami

You can use dotenv package for this purpose

Reference: https://www.npmjs.com/package/dotenv https://github.com/motdotla/dotenv

At top of webpack config file, require dotenv as follows(set your .env path currectly)

var dotenv = require('dotenv').config({path: __dirname + '/.env'});

in webpack config plugins section use

new webpack.DefinePlugin({
            "process.env": dotenv.parsed
        }),

Now you can use the env variables throughout your app. try console.log(process.env); in you app code

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,
    }),
    // ...
]

I can't comment to clarify any info so my apologies for the answer.

You could do:

var env = require('.env');

then

new webpack.DefinePlugin({
            "API_URL": JSON.stringify("http://my-api.com"),
            "SECRET_KEY" : "MYSECRETKEYGOESHERE",
            "env_property": env.property
        }),

But I'm making assumptions about your .env file and the way its set up with this answer

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)
    })
]

...

From webpack docs:

The webpack command line environment option --env allows you to pass in as many environment variables as you like. Environment variables will be made accessible in your webpack.config.js. For example, --env.production or --env.NODE_ENV=local (NODE_ENV is conventionally used to define the environment type, see here.)

in your package.json

webpack --env.NODE_ENV=local --env.production --progress

in your webpack.config.js

module.exports = env => {
  // Use env.<YOUR VARIABLE> here:
  console.log('NODE_ENV: ', env.NODE_ENV) // 'local'
  console.log('Production: ', env.production) // true

  return {
    entry: './src/index.js',
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist')
    }

The simplest solution I found is to use this npm package: dotenv-webpack

Create a .env file

// .env
DB_HOST=127.0.0.1
DB_PASS=foobar
S3_API=mysecretkey

Add it to your Webpack config file

// webpack.config.js
const Dotenv = require('dotenv-webpack');

module.exports = {
...
plugins: [
new Dotenv()
]
...
};

Use in your code

// file1.js
console.log(process.env.DB_HOST);
// '127.0.0.1'
Resulting bundle
// bundle.js
console.log('127.0.0.1');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!