How to pass .env file variables to webpack config?

后端 未结 7 898
旧时难觅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: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,
        }),
        // ...
    ]
    

提交回复
热议问题