我使用react和flux架构创建了一个项目。需要对bundle.js文件进行分块,因为通过组合所有文件,它创建了一个4mb的巨大js文件,这导致在慢速网络上下载时出现问题,因此如何将js文件块化,以便在页面中只包含所需的库打开 我正在使用webpack 1.x
我的目录结构是
webpack.config.js文件
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'cheap-module-source-map',
entry: [
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: ''
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.CommonsChunkPlugin({
// names: ["app", "subPageA"]
// (choose the chunks, or omit for all chunks)
children: true,
// (use all children of the chunk)
async: true,
// (create an async commons chunk)
// minChunks: 3,
// (3 children must share the module before it's separated)
})
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'src')
}, {
test: /\.css$/,
exclude: /\.useable\.css$/,
loader: "style-loader!css-loader"
}, {
test: /\.useable\.css$/,
loader: "style-loader/useable!css-loader"
}, {
test: /\.png$/,
loaders: ["url-loader?mimetype=image/png"]
}, {
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
}]
}
};

server.js文件
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
}).listen(3000, 'localhost', function(err, result) {
if (err) {
return console.log(err);
}
console.log('Listening at http://localhost:3000/');
});

index.html文件
<html>
<head>
<title>Project</title>
</head>
<body>
<div id="app" />
<script src="bundle.js" type="text/javascript"></script>
</body>
</html>
&#13;
答案 0 :(得分:1)
当您需要特定模块时,初始加载时不需要该模块,您可以使用
require.ensure(["module-a", "module-b"], function() {
var a = require("module-a");
// ...
});
这样它只会在您需要时加载,从而减少您的包大小。
如果使用路由和react-router,则可以按照本文所述使用每个路由代码拆分 documentation
答案 1 :(得分:0)
我的经验,通常使用webpack-optimize-chunk-plugin,您将项目代码拆分为vendor.js和bundle.js。像这样:
module.exports = {
entry:{
vendor: ["react", "react-dom"], // list all vender libraries here
app: ['./path/to/entry.js']
},
output: {
path: path.join(__dirname, './public'),
filename:'bundle.js'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js")
]
}
所以这会输出一个bundle.js和一个vendor.js。我没有看到你所描述的方式使用的webpack-optimize-chunk-plugin。 (如果可能,这将是非常酷的。)
另外,我会检查所有其他webpack优化插件,以帮助完成所有文件大小。 (即DedupePlugin,UglifyJsPlugin,OccurenceOrderPlugin ......)。更多信息here。此外,here是您可能会发现有用的多入口点示例。祝你好运。