Setting process.env.NODE_ENV

為了實作 DefinePlugin 的概念,可以宣告像 if(process.env.NODE_ENV === 'development') 這樣的述句。

透過使用 DefinePlugin,可以把 process.env.NODE_ENV 換成 'development',讓述句為 true

跟之前一樣,把 function 寫在 parts.js:

libs/parts.js

...

exports.setFreeVariable = function(key, value) {
  const env = {};
  env[key] = JSON.stringify(value);

  return {
    plugins: [
      new webpack.DefinePlugin(env)
    ]
  };
}

然後在 webpack.config.js 做設定:

...

// Detect how npm is run and branch based on that
switch(process.env.npm_lifecycle_event) {
  case 'build':
    config = merge(
      common,
      {
        devtool: 'source-map'
      },

      parts.setFreeVariable(
        'process.env.NODE_ENV',
        'production'
      ),

      parts.minify(),
      parts.setupCSS(PATHS.app)
    );
    break;
  default:
    ...
}

module.exports = validate(config);

執行 npm run build,你會看到更具優化的結果:

[webpack-validator] Config is valid.
Hash: 9880a5782dc874c824c4
Version: webpack 1.13.0
Time: 3004ms
     Asset       Size  Chunks             Chunk Names
    app.js    25.4 kB       0  [emitted]  app
app.js.map     307 kB       0  [emitted]  app
index.html  157 bytes          [emitted]
   [0] ./app/index.js 123 bytes {0} [built]
  [36] ./app/component.js 136 bytes {0} [built]
    + 35 hidden modules
Child html-webpack-plugin for "index.html":
        + 3 hidden modules

原本一開始 app.js 有 133 kB,然後降到 38 kB,最後只剩 25.4 kB,而且最後 build 的時候應該有明顯地比之前處理的還要快。

Babel 的 babel-plugin-transform-inline-environment-variables plugin 也可以達成相同的效果。更多資訊詳見 the official documentation

注意在我們的 Build 中,少了 react-dom,在實作上,React 的應用程式其實會很明顯的肥大,除非使用輕量化的版本例如:preactreact-lite,這些版本可能會缺少一些功能,但如果使用 React,值得了解一下。

results matching ""

    No results matching ""