简体   繁体   English

Webpack:-p vs NODE_ENV =生产vs process.env.NODE_ENV

[英]Webpack: -p vs NODE_ENV=production vs process.env.NODE_ENV

I'm having an issue with webpack in production and I'm getting confused with the different ways of running webpack in the production environment (I'm using Windows). 我在生产中遇到了webpack 的问题 ,并且对在生产环境中运行webpack的不同方式感到困惑(我使用的是Windows)。

Can someone explain the difference between these: 有人可以解释一下两者之间的区别:

One: CLI 一:CLI

  • webpack -p

Two: CLI 二:CLI

  • SET NODE_ENV=production
  • webpack

Three: webpack.config.js 三:webpack.config.js

new webpack.ProvidePlugin({
  'process.env': {
    NODE_ENV: JSON.stringify('production')
  }
})

I'm using React and need to build a production version which is both minified and includes the production version of React. 我正在使用React,并且需要构建一个最小化的生产版本,并包括React的生产版本。

SET NODE_ENV=production sets NODE_ENV environment variable to "production" on the server. SET NODE_ENV=production在服务器上将NODE_ENV环境变量设置为“ production”。 The machine that compiles and bundles your javascript source files. 编译并捆绑javascript源文件的机器。 So it can for example select a different webpack config file for production. 因此,它可以例如选择用于生产的其他Webpack配置文件。

But this enviroment variable has no effect when this javascript code actually runs. 但是,此javascript代码实际运行时,此环境变量无效。 Because the javascript code will run on a browser in a different machine. 因为javascript代码将在其他计算机上的浏览器上运行。

The providePlugin helps to set NODE_ENV variable in the browser. ProvidePlugin帮助在浏览器中设置NODE_ENV变量。 Where your javascript actually runs. 您的JavaScript实际运行的位置。 Actually what it really does is replacing occurences of process.env.NODE_ENV with "production" rather than setting a variable. 实际上,它真正要做的是用"production"代替process.env.NODE_ENV ,而不是设置变量。 But effects are same. 但是效果是一样的。

EDIT : It's actually DefinePlugin that should be used for this purpose. 编辑 :实际上是应该用于此目的的DefinePlugin

Weback -p advertises to doing the second of above but seems to have some issues . Weback -p做广告做上述第二件事,但似乎有一些问题

Based on webpack documentation setting webpack -p performs following 基于webpack文档设置webpack -p执行以下操作

  • Minification using UglifyJSPlugin 使用UglifyJSPlugin缩小
  • Runs the LoaderOptionsPlugin 运行LoaderOptionsPlugin
  • Sets the Node environment variable 设置节点环境变量

So instead of doing: 因此,与其做:

"scripts": {
  "dist": "NODE_ENV=production webpack",
  "start": "webpack"
}

You can just specify 您可以只指定

"scripts": {
  "dist": "webpack -p",
  "start": "webpack"
}

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

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