require.ensure()引入的多个模块,打包后为什么会把所有使用require.ensure()的模块都打成包成一个文件了?
具体如下:
app.js
home.js(它里面已经包括了home.js和about.js的代码)
vendors
我希望打包后require.ensure()加载的文件能分别输出,
如:
home.js
about.js
webpack如下(片段):
//静态资源地址
baseConfig.output.publicPath = '/assets/';
baseConfig.output.filename = '[name].[chunkhash:8].js';
baseConfig.output.chunkFilename = '[name].[chunkhash:8].js';
let config = Object.assign({}, baseConfig, {
entry: {
vendors : ['core-js', 'react', 'react-dom', 'react-router', 'react-cookie', 'react-tap-event-plugin', 'whatwg-fetch'], //抽公共库
app : path.join(__dirname, '../src/index')
},
cache: true,
devtool : null,
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendors','[name].[chunkhash:8].js'),
new ExtractTextPlugin('styles.[chunkhash:8].css',{allChunks: true}),
new WebpackMd5Hash()
]
});
代码结构如下:
rootRoute.js
const rootRoute = {
component: 'div',
childRoutes: [ {
path: '/',
component: require('components/Main'),
childRoutes: [
require('./homeRoute'),
require('./aboutRoute')
]
} ]
}
module.exports = rootRoute;
homeRoute.js
module.exports = {
path: 'home',
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('components/Home'))
}, 'home')
}
}
aboutRoute.js
module.exports = {
path: 'about',
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('components/About'))
}, 'about')
}
}
components/home.js
import React, { PropTypes } from 'react'
const Home = React.createClass({
render () {
return (
<div>
<h1>Home</h1>
</div>
)
}
})
module.exports = Home
components/about.js
import React, { PropTypes } from 'react'
const About = React.createClass({
render () {
return (
<div>
<h1>About</h1>
</div>
)
}
})
module.exports = About
自己找到问题所在了,原来webpack里有加载了这个plugin:
new webpack.optimize.AggressiveMergingPlugin()
查了一下文档,原来就是它把所有的chunkFile又合到一起了。