微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将 webpack 块图导出到 json

如何解决将 webpack 块图导出到 json

问题:如何在不解析最终包的情况下提前获取依赖块图?最好是 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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。