How to pass .env file variables to webpack config?

后端 未结 7 855
旧时难觅i
旧时难觅i 2020-12-05 05:18

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

相关标签:
7条回答
  • 2020-12-05 05:30

    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

    0 讨论(0)
  • 2020-12-05 05:33

    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');
    
    0 讨论(0)
  • 2020-12-05 05:34

    First off...

    It appears that you are trying to pass secrets into an angular application.

    There is no such thing as a "secret" in client side (browser) javascript!!!

    Anything passed into DefinePlugin can be extracted with minimal effort.

    Now that we've cleared that up....

    Webpack now has the Environment Plugin which makes it a bit easier to pass env variables into the GlobalDefine plugin. From the docs:

    new webpack.EnvironmentPlugin(['NODE_ENV', 'DEBUG']);
    

    This is equivalent to the following DefinePlugin application:

    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
      'process.env.DEBUG': JSON.stringify(process.env.DEBUG)
    });
    

    If you are using dotenv to manage environment vars, you can use the dotenv webpack plugin.

    It will only include variables that are referenced in your code, so as long as you don't reference your secrets, they won't be included.

    0 讨论(0)
  • 2020-12-05 05:35

    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')
        }
    
    0 讨论(0)
  • 2020-12-05 05:41

    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,
        }),
        // ...
    ]
    
    0 讨论(0)
  • 2020-12-05 05:47

    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

    0 讨论(0)
提交回复
热议问题