Javascript 将命令行参数传递给 webpack.config.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44113359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:20:57  来源:igfitidea点击:

Passing command line arguments to webpack.config.js

javascriptwebpack

提问by user1934212

I have a simple webpack.config.js

我有一个简单的 webpack.config.js

module.exports = {
  entry: "./app.js",
  output: {
    filename: "bundle.js"
  },
}

And I want to pass the values for entryand outputthrough command line arguments. Is that possible and how would I do that?

我想通过值entryoutput通过命令行参数。这可能吗,我该怎么做?

回答by Axnyff

webpack.config.jscan also exports a function of env which can return a conf object. You can therefore have a webpack config like:

webpack.config.js也可以导出一个可以返回 conf 对象的 env 函数。因此,您可以拥有一个 webpack 配置,例如:

module.exports = env => {
    return {
        entry: env === "production" ? "./app.js": "app-dev.js",
        output: {
          filename: "bundle.js"
        },
    }
};

and then call webpack from command-line (or package.json) like this:

然后像这样从命令行(或 package.json)调用 webpack:

webpack --env=production

回答by PRAISER

You may use argvpackage and set the variables. You must do it before module.export.

您可以使用argv包并设置变量。你必须这样做module.export

回答by adrian

You can provide custom parameters on the envvariable from the command line, so for this example you could call:

您可以env从命令行为变量提供自定义参数,因此对于此示例,您可以调用:

webpack --env.entry='./app.js' --env.output='bundle.js'

webpack --env.entry='./app.js' --env.output='bundle.js'

and use them in your webpack by doing

并通过执行在您的 webpack 中使用它们

module.exports = env => ({
  entry: env.entry,
  output: {
    filename: env.output
  },
});