我已經使用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