我已经使用react和flux架构创建了一个项目。需要将bundle.js文件分块,因为通过组合所有文件,它将创建一个4mb的巨大js文件,这会导致在慢速网络上下载时出现问题,因此如何分块js文件,以便在页面中只包含所需的库打开 我使用的WebPack 1.x的如何分块bundle.js文件?
我的目录结构是
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>
你能给我一个例子使用我的代码 – Gagan
你的代码不会透露你的应用程序的任何js提出建议。但是,代码拆分的常见用例是,当您在内容的下方滚动内容时,需要确保您在内容中放置“内容不足”内容。或者当用户点击某个按钮并导致某个组件以其大逻辑出现在屏幕上时。在React中,尽管你通常使用反应路由器分裂来处理代码分割。但是你也可以通过需求保证加载第三方库。 – sergeysmolin