【发布时间】:2015-09-08 02:33:26
【问题描述】:
场景
我正在尝试使用 webpack 将我的供应商脚本与我的应用程序脚本分开捆绑。
尝试 1
index.js
var _ = require('lodash');
console.log(_)
webpack.config.js
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var config = {
entry: {
vendor: ['lodash'],
app: './index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[chunkhash].js'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
minChunks: Infinity,
}),
new HtmlWebpackPlugin({
filename: 'index.html',
inject: true
})
]
};
module.exports = config;
结果
Asset Size Chunks Chunk Names app.3437c5da57e0c6671675.js 145 bytes 0 [emitted] app vendor.72c95e21a8d7096d53bc.js 428 kB 1 [emitted] vendor index.html 232 bytes [emitted]
现在,如果我更改为 index.js
index.js
var _ = require('lodash');
console.log('changed index');
console.log(_)
结果
Asset Size Chunks Chunk Names app.c724350371b50a9afeb2.js 177 bytes 0 [emitted] app vendor.0e76f9c86cbe02606265.js 428 kB 1 [emitted] vendor index.html 232 bytes [emitted]
即使我只更新了索引文件,两个哈希值也会发生变化。
两个vendor文件的区别是
vendor.72c95e21a8d7096d53bc.js
script.src = __webpack_require__.p + "" + chunkId + "." + ({"0":"app"}[chunkId]||chunkId) + "." + {"0":"3437c5da57e0c6671675"}[chunkId] + ".js";
vendor.0e76f9c86cbe02606265.js
script.src = __webpack_require__.p + "" + chunkId + "." + ({"0":"app"}[chunkId]||chunkId) + "." + {"0":"c724350371b50a9afeb2"}[chunkId] + ".js";
尝试 2
在做了一些研究后,我发现下面的文章解释了 webpack 生成一个包含块标识符的卡盘清单,该块标识符被放置在入口块中。这解释了上面的差异。解决方案是将卡盘清单提取到单独的文件中。
https://medium.com/@okonetchnikov/long-term-caching-of-static-assets-with-webpack-1ecb139adb95
index.js
var _ = require('lodash');
console.log(_)
webpack.config.js
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ChunkManifestPlugin = require('chunk-manifest-webpack-plugin');
var config = {
entry: {
vendor: ['lodash'],
app: './index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[chunkhash].js'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
minChunks: Infinity,
}),
new ChunkManifestPlugin({
filename: "manifest.json",
manifestVariable: "webpackManifest"
}),
new HtmlWebpackPlugin({
filename: 'index.html',
inject: true
})
]
};
module.exports = config;
结果
Asset Size Chunks Chunk Names app.3437c5da57e0c6671675.js 145 bytes 0 [emitted] app manifest.json 35 bytes [emitted] vendor.72c95e21a8d7096d53bc.js 428 kB 1 [emitted] vendor
现在,如果我更改 index.js
index.js
var _ = require('lodash');
console.log('changed index');
console.log(_)
结果
Asset Size Chunks Chunk Names app.c724350371b50a9afeb2.js 177 bytes 0 [emitted] app manifest.json 35 bytes [emitted] vendor.0e76f9c86cbe02606265.js 428 kB 1 [emitted] vendor
即使我只更新了索引文件,两个哈希值也再次发生变化。
但这一次,两个供应商文件之间没有区别
问题
上述方案不起作用是有原因的,还是我从根本上错误地解决了这个问题。
使用 webpack 是否有更简单的方法来实现我想要做的事情,因为即使我完成了上述步骤,我也必须阅读清单,然后将其注入我的 index.html 页面?
【问题讨论】:
标签: webpack