简体   繁体   English

在 webpack 构建中从 cli 向 js 添加变量

[英]add variable to js from cli in webpack build

I'm trying to add a variable to my app.js at the time of build.我试图在构建时向我的 app.js 添加一个变量。 For example:例如:

//app.js
var myvar = {{set_from_cli}};

then I want to run something like webpack -p --myvar='abc' which would result in this:然后我想运行类似webpack -p --myvar='abc' ,这会导致:

//bundle.js
var myvar = 'abc';

I've searched and maybe I'm just not looking in the right places or using the right terms, but can't figure out how to do this.我已经搜索过,也许我只是没有在正确的地方寻找或使用正确的术语,但无法弄清楚如何做到这一点。

You can access myvar at webpack.config.js like this (assuming minimist ):您可以像这样访问myvar中的myvar (假设minimist ):

var argv = require('minimist')(process.argv.slice(2));
console.log(argv.myvar);

To get it to your bundle, you can use the DefinePlugin .要将其添加到您的包中,您可以使用DefinePlugin You would need to have something like this at your plugin definition:你需要在你的插件定义中有这样的东西:

plugins: [
    new webpack.DefinePlugin({
      MYVAR: JSON.stringify(argv.myvar)
    })
]

Then at code然后在代码

var myvar = MYVAR;

Adjust as necessary.根据需要进行调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM