我的Webpack配置中有多个条目:
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
},
当我运行npm start
(webpack-dev-server --inline --progress --port 8080 --bail
)时,我的index.html中的\<my-app>Loading...</my-app>
将按此顺序转换为脚本:
<script type="text/javascript" src="http://localhost:8080/common.js"> <!--I also have CommonsChunkPlugin-->
</script><script type="text/javascript" src="http://localhost:8080/vendor.js"></script>
<script type="text/javascript" src="http://localhost:8080/polyfills.js"></script>
<script type="text/javascript" src="http://localhost:8080/app.js"></script>
但是当我按照这个顺序运行webpack -p --progress --profile --bail
时:
common,app,polyfil,然后是供应商</ em>
订单很重要。如果在polyfil.js或vendor.js之前运行,我的app.js代码将无效。 如何控制订单?
答案 0 :(得分:5)
您可以创建一个帮助程序来完成它:
function packageSort(packages) {
// packages = ['polyfills', 'vendor', 'app']
var len = packages.length - 1;
var first = packages[0];
var last = packages[len];
return function sort(a, b) {
// polyfills always first
if (a.names[0] === first) {
return -1;
}
// app always last
if (a.names[0] === last) {
return 1;
}
// vendor before app
if (a.names[0] !== first && b.names[0] === last) {
return -1;
} else {
return 1;
}
}
}
在你的webpack配置文件中:
plugins.index = new HtmlWebpackPlugin({
template: 'src/index.html',
filename: 'index.html',
chunksSortMode: packageSort(['polyfills', 'vendor', 'app'])
});
答案 1 :(得分:4)
您可以使用&#39;手册&#39;选择这些天:
new HtmlWebpackPlugin({
chunks: ['polyfill', 'vendor', 'bundle'],
chunksSortMode: 'manual',
}),
答案 2 :(得分:3)
感谢@EdmarMiyake将我指向chunksSortMode的方向。我尝试将其设置为依赖&#39;首先,但这似乎没有用。最后我采取了这个:
function packageSort(packages) {
return function sort(left, right) {
var leftIndex = packages.indexOf(left.names[0]);
var rightindex = packages.indexOf(right.names[0]);
if ( leftIndex < 0 || rightindex < 0) {
throw "unknown package";
}
if (leftIndex > rightindex){
return 1;
}
return -1;
}
};
和
new HtmlWebpackPlugin({
template: 'src/index.html',
chunksSortMode: packageSort(['common', 'polyfills', 'vendor', 'app'])
}),
答案 3 :(得分:0)
此功能可能更好:您首先在html文件中提供要放置的元素列表
function packageSort(packages) {
return function sort(left, right) {
var leftIndex = packages.indexOf(left.names[0]);
var rightindex = packages.indexOf(right.names[0]);
if (rightindex < 0) {
return -1;
}
if ( leftIndex < 0) {
return 1;
}
if (leftIndex > rightindex){
return 1;
}
return -1;
}
};