优化对生产的React Webpack配置

问题描述 投票:0回答:1

我的Web生产webpack配置如下所示:

const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
const WebpackStrip = require('strip-loader');

module.exports = [
{
    devtool: 'cheap-module-source-map',
    entry: './ui/moduleTest/entry.js',
    output: { path: __dirname + '/public/compiled', filename: 'mod1bundle.js' },
    module: {
    loaders: [
         { test: /\.jsx?$/, loader: 'babel-loader', include: /ui/, query: { presets: ['es2015', 'stage-0', 'react'] } },
         { test: /\.scss$/, loader: ExtractTextPlugin.extract( "style", "css!sass") }
     ]
         },
    plugins: [
       new ExtractTextPlugin("styles.css"),
       new webpack.optimize.UglifyJsPlugin()
    ]
   }, 
 { devtool: 'cheap-module-source-map',
   entry: './ui/moduleTest2/entry.js',
   output: { path: __dirname + '/public/compiled', filename: 'mod2bundle.js' },
   module: {
        loaders: [
             { test: /\.jsx?$/, loader: 'babel-loader', include: /ui/, query: { presets: ['es2015', 'stage-0', 'react'] } },
           ]
   },
   plugins: [
         new ExtractTextPlugin("styles.css"),
         new ExtractTextPlugin("console.log"),
         new webpack.optimize.UglifyJsPlugin()
        ]
    },
   ....
  ];

我尝试了很多事情,但无法将其投入生产。 react dev工具告诉我我正在使用react的dev版本。 我是webpack的新手。 我还需要关闭console.log消息。 关于如何将此配置转换为生产环境的任何想法? 我已经读了很多东西,但是我有很多问题需要理解。 我正在使用类似的命令:

  webpack --config=webpack.prod.config.js --watch --progress --watch-poll -p

编译我的代码

reactjs webpack
1个回答
1
投票

您需要看一下DefinePlugin

它的工作是查找给定字符串的实例,然后将其替换为其他字符串。 将此代码添加到您的插件数组以对其进行配置,以构建React的生产版本。

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

然后确保您也在使用UglifyJS插件,并且该插件位于配置中的DefinePlugin之后。

这将替换以下所有表达式:

if (process.env.NODE_ENV === "development") {
  // do slow development code
}

使用如下代码:

if ("production" === "development") {
  // do slow development code
}

Uglify可以在编译时将其识别为if表达式,它将永远不会为真,并删除整个语句。

如果要删除所有console.log语句,最简单的方法是在初始化文件中将其设置为no op。

if (process.env.NODE_ENV === "production") {
  console.log = () => {};
  console.info = () => {};
  // ...
}

确保此代码在任何可能包含日志记录语句的文件之前运行。

© www.soinside.com 2019 - 2024. All rights reserved.