问:如何在不解析最终包的情况下提前获得依赖块图?最好的方法是使用json。
原因:
使用webpack的默认分块策略,它可以创建多个其他分块所依赖的公共分块。例如,两个动态导入,如
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">当我向用户发送一个需要'bar‘的html页面时,我想添加:
<script src="chunk/bar.js"></script><script src="chunk/bar.0.js">正因为如此,脚本已经在html解析时加载,并且在第一次执行javascript时不需要额外的往返。
但是,如何在不解析最终包的情况下提前获得依赖块图呢?
发布于 2021-02-25 23:30:29
如果无法从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>https://stackoverflow.com/questions/66338746
复制相似问题