How to pass .env file variables to webpack config?

后端 未结 7 891
旧时难觅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: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');
    

提交回复
热议问题