我正在尝试通过使用webpack(特别是我的节点模块)拆分代码,并将每个模块拆分为自己的捆绑包来优化网站的速度性能。
对于我们自己的代码库来说,捆绑包分割工作得很好,但是当我分割节点模块时,浏览器显示一个空白页面,没有错误。已成功获取主捆绑包,但似乎无法正确执行。
这是我的webpack配置文件:
var webpack = require('webpack');
var path = require('path');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const CompressionPlugin = require('compression-webpack-plugin');
var BUILD_DIR = path.resolve(__dirname, 'static/public/js');
var APP_DIR = path.resolve(__dirname, 'static/js');
var CSS_DIR = path.resolve(APP_DIR, 'css');
var config_function = function(env){
var config = {
mode: env && env.prod ? 'production':'development',
entry: ['babel-polyfill', APP_DIR + '/index.js'],
output: {
path: BUILD_DIR,
filename: env && env.prod ? '[name].bundle.min.js' : '[name].bundle.js',
publicPath: '/static/js/'
},
optimization: {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups:{
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
return `npm.${packageName.replace('@', '')}`;
},
}
}
}
},
plugins: env && env.prod ? [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"'
}),
new UglifyJSPlugin({uglifyOptions:{
ecma: 5,
mangle: {
safari10: true
},
warnings: false,
screw_ie8: true,
compress: true,
}}),
new CompressionPlugin({
algorithm: 'gzip',
minRatio: 1})
]: [
new BundleAnalyzerPlugin(),
],
module: {
rules: [{
test: /\.jsx?/,
include: [APP_DIR, /node_modules\/snakecase-keys/, /node_modules\/redux-api-middleware/,/node_modules\/map-obj/, /node_modules\/hare-niemeyer/, /node_modules\/round-to/, /node_modules\/styled-components/],
loader: 'babel-loader',
query: {
presets: ['es2015', 'react', 'stage-2'], //, 'react-hmre']
plugins: ['recharts']
}
}, {
test: /\.scss$/,
loaders: ['style-loader', 'css-loader', 'sass-loader']
}, {
test: /\.json$/,
loader: 'json-loader',
type: 'javascript/auto'
}, {
test: /\.less$/,
include: CSS_DIR,
loaders: ['style-loader', 'css-loader', 'less-loader']
}, {
test: /\.css$/,
loaders: ['style-loader', 'css-loader']
}, {
test: /\.(png|jpg)$/,
loader: 'url-loader'
},
]
}
};
return config;
}
module.exports = config_function;
代码拆分看起来完全符合我的预期:每个npm软件包都有自己的捆绑包,其余代码也可以成功拆分。但是,它只是没有按预期执行(即,无错误的空白页)。
答案 0 :(得分:0)
我误解了这项技术,并认为运行时捆绑包负责动态获取各个npm模块。
必须通过index.html文件中的脚本来获取每个npm模块,以使其正常工作。