How to pass .env file variables to webpack config?

后端 未结 7 892
旧时难觅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: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.

提交回复
热议问题