如何使用webpack转换生产文件?

时间:2017-10-08 07:58:07

标签: reactjs webpack

运行我在带有React 16的webpack 3.6.0中构建的应用程序时遇到的问题类似于this SO post。 Webpack构建运行正常,但在任何浏览器上运行应用程序时,即使指定了Uncaught ReferenceError: require is not defined选项,我也会收到noParse脚本错误。这只发生在生产文件中。开发模式在浏览器中运行该应用就好了。所以,我不太清楚我错过了什么。

如果有人能指出我的错误,我真的很感激。以下是我的webpack配置代码,.babelrc和package.json脚本代码:

webpack.config.base.js

'use strict';

const path = require( 'path' );
const webpack = require( 'webpack' );

let NODE_ENV = process.env.NODE_ENV;

let env = {
    production  : NODE_ENV === 'production',
    staging     : NODE_ENV === 'staging',
    test        : NODE_ENV === 'test',
    development : NODE_ENV === 'development' || typeof NODE_ENV === 'undefined'
};

Object.assign(
    env, {
        build : (env.production || env.staging)
    }
);

let config = {
    context   : __dirname,
    entry     : {
        'vendor' : [
            'babel-polyfill',
            'html5shiv',
            'react',
            'react-dom',
            'bootstrap',
            'redux',
            'react-redux',
            'redux-saga',
        ],
        'app'    : './src/app/App.js',
    },
    output    : {
        path          : __dirname + '/dev',
        filename      : '[name]/index.js',
        //chunkFilename : 'partials/[name].js' + (env.development ? '?ver=[chunkhash]' : ''),
        chunkFilename : 'partials/[name].js',
    },
    externals : {
        jquery : 'jQuery',
    },
    resolve   : {
        extensions       : ['.webpack.js', '.web.js', '.js', '.jsx'],
        moduleExtensions : [
            'node_modules',
            path.resolve( __dirname, './node_modules' ),
        ],
    },
    devtool   : 'eval-source-map',
    module    : {
        rules   : [
            {
                test    : /(\.js|\.jsx)$/,
                exclude : /(node_modules)/,
                loader  : 'babel-loader',
                /*query   : { presets : ['env', 'stage-1', 'react'] }*/
            },
            {
                test   : /\.json$/,
                loader : 'json-loader'
            },
            {
                test   : /\.css$/,
                loader : "style-loader!css-loader"
            },
            {
                test : /(\.scss|\.sass)$/,
                use  : [
                    {
                        loader : 'style-loader', // inject CSS to page
                    },
                    {
                        loader : 'css-loader', // translates CSS into CommonJS modules
                    },
                    {
                        loader  : 'postcss-loader', // Run post css actions
                        options : {
                            plugins : function () { // post css plugins, can be exported to postcss.config.js
                                return [
                                    require( 'precss' ),
                                    require( 'autoprefixer' )
                                ];
                            }
                        }
                    },
                    {
                        loader : 'sass-loader' // compiles SASS to CSS
                    }
                ]
            },
        ],
        noParse : /\.min\.js/
    },
    plugins   : [
        new webpack.NoEmitOnErrorsPlugin(),
        new webpack.ProvidePlugin(
            {
                React           : 'react',
                ReactDOM        : 'react-dom',
                $               : 'jquery',
                jQuery          : 'jquery',
                'window.jQuery' : 'jquery',
                Popper          : ['popper.js', 'default'],
                Tether          : 'tether',
            }
        ),
        new webpack.optimize.CommonsChunkPlugin(
            {
                names     : 'vendor',
                //filename  : '[name].[chunkhash].js',
                minChunks : function ( module ) {
                    // this assumes your vendor imports exist in the node_modules directory
                    return module.context && module.context.indexOf( 'node_modules' ) !== -1;
                },
                children  : true,
                async     : true,
            }
        ),
        new webpack.optimize.CommonsChunkPlugin(
            {
                names     : 'manifest',
                minChunks : Infinity
            }
        ),
        new webpack.DefinePlugin(
            {
                __DEV__         : env.development,
                __STAGING__     : env.staging,
                __PRODUCTION__  : env.production,
                __CURRENT_ENV__ : '\'' + (NODE_ENV) + '\''
            }
        )
    ]
};

module.exports = config;

webpack.config.production.js

'use strict';
const webpack = require( 'webpack' );
const config = require( './webpack.config.base.js' );
const CleanWebpackPlugin = require( 'clean-webpack-plugin' );

config.output = {
    path          : __dirname + '/dist',
    filename      : '[name]/index.js',
    chunkFilename : 'partials/[id].[chunkhash:8].js',
};

config.devtool = 'cheap-module-source-map';

config.plugins = config.plugins.concat(
    [
        /*new webpack.optimize.UglifyJsPlugin(
            {
                output   : {
                    comments : false
                },
                compress : {
                    warnings  : false,
                    screw_ie8 : true
                }
            }
        ),*/
        new webpack.DefinePlugin(
            {
                'process.env' : {
                    NODE_ENV : JSON.stringify( 'production' )
                }
            }
        ),
        new CleanWebpackPlugin( ['dist'], {
            root    : __dirname,
            verbose : true,
            dry     : false,
            exclude : [],
            watch   : true,
        } ),
    ]
);

module.exports = config;

.babelrc

{
  "presets": [
    "react",
    "stage-1",
    [
      "env",
      {
        "targets": {
          "browsers": [
            "last 2 versions"
          ]
        },
        "debug": true,
        "modules": "commonjs"
      }
    ]
  ],
  "plugins": [
    "transform-class-properties"
  ]
}

package.json脚本

{
  ...
  "scripts": {
    "build": "cross-env NODE_ENV=production webpack --progress",
    "watch": "cross-env NODE_ENV=development webpack --debug --output-pathinfo --progress --watch",
    "build-dev": "cross-env NODE_ENV=development webpack --debug --output-pathinfo --progress",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  ...
}

1 个答案:

答案 0 :(得分:0)

通过评论/删除noParse : /\.min\.js/行来完成工作。奇怪/有趣,但工作。