问题描述
问题:如何在不解析最终包的情况下提前获取依赖块图?最好是 json。
为什么:
使用 webpacks 默认的块分割策略,它创建多个其他块所依赖的公共块。例如。两个动态导入如
const foo = () => import('./foo');
const bar = () => import('./bar');
webpack 可能会重写为(不完全是,但作为一个概念):
const foo = () => __webpack.r(['foo','bar']);
const bar = () => __webpack.r(['bar','bar.0']);
所以 webpack 注意到 foo 重用了 'bar' 的一部分并创建了一个 'bar.0',模块只用于 bar 并重用了块 'bar' 中的所有内容。
当我向用户发送一个 html 页面时,我肯定知道它会需要“foo”,我想添加:
<script src="chunk/foo.js"></script><script src="chunk/bar.js">
当我向用户发送一个 html 页面时,我知道它需要“bar”,我想添加:
<script src="chunk/bar.js"></script><script src="chunk/bar.0.js">
这样脚本就已经在 html 解析时加载了,并且在第一次执行 javascript 时不依赖额外的往返。
但是如何在不解析最终包的情况下提前获取依赖块图?
解决方法
如果没有办法从 webpack 访问块图,我必须手动定义公共块。大致如下:
function extraChunkForCodeReuse(name: string,chunks: RegExp): Record<string,webpack.Options.CacheGroupsOptions> {
const cacheGroup: webpack.Options.CacheGroupsOptions = {
name,priority: -20,minChunks: 3,reuseExistingChunk: false,chunks: (chunk) => chunks.test(chunk.name),};
return {[`${name}`]: cacheGroup};
}
const config = {
optimization: {
splitChunks: {
cacheGroups: {
// the default code reuse strategy is very good,but the chunk names are nondeterministic thus we can't reliably preload them
// via <script> tags from twig:
default: false,// define custom reuse chunks that we can embed via <script> tag
...extraChunkForCodeReuse('shared-foo',/foo|bar|baz/),...extraChunkForCodeReuse('shared-checkout',/checkout/),},};
那我就可以了
// template that needs the foo chunk
<script src="/shared-foo.js"></script>
<script src="/foo.js"></script>
<script src="/main.js"></script>
// template that needs the checkout chunk
<script src="/shared-checkout.js"></script>
<script src="/checkout.js"></script>
<script src="/main.js"></script>