2

我正在尝试将svg-chunk-webpack-pluginwebpack v4 更新到 v5。该插件使用了编译对象,并且需要一个按入口点过滤的文件依赖项的平面列表,以提取每个入口点的所有 SVG。

具有入口点的嵌套依赖树示例app-a

- app-a.js
    - svg1.svg
    - module1.js
        - svg2.svg
        - svg3.svg
        - module2.js
            - svg4.svg
            - svg5.svg

使用webpackv4,以下代码可以工作并返回每个入口点使用的所有 SVG 文件的数组

const path = require('path');

function getSvgsDependenciesByEntrypoint(entryName) {
    let listSvgs = [];

    compilation.entrypoints.get(entryName).chunks.forEach((chunk) => {
        chunk.getModules().forEach((module) => {
            module.buildInfo &&
                module.buildInfo.fileDependencies &&
                module.buildInfo.fileDependencies.forEach((filepath) => {
                    const extension = path.extname(filepath).substr(1);
                    if (extension === 'svg') {
                        listSvgs.push(filepath);
                    }
                });
        });
    });
    return listSvgs;
}

const svgs = getSvgsDependenciesByEntrypoint('app-a');
console.log(svgs) // ["svg1.svg", "svg2.svg", "svg3.svg", "svg4.svg", "svg5.svg"]

使用webpackv5,我尝试了以下代码,这些代码在开发和生产构建之间产生了不同的结果。

const path = require('path');

function getSvgsDependenciesByEntrypoint(entryName) {
    let listSvgsDependencies = [];

    compilation.entrypoints.get(entryName).chunks.forEach((chunk) => {
        compilation.chunkGraph.getChunkModules(chunk).forEach((module) => {
            module.dependencies.forEach((dependency) => {
                const extension = path.extname(dependency.userRequest).substr(1);
                if (extension === 'svg') {
                    const moduleDependency = compilation.moduleGraph.getModule(dependency);
                    listSvgsDependencies.push(moduleDependency);
                }
            });
        });
    });

    return listSvgsDependencies;
}

正在开发中

const svgs = getSvgsDependenciesByEntrypoint('app-a');
console.log(svgs) // ["svg1.svg", "svg2.svg", "svg3.svg", "svg4.svg", "svg5.svg"]

在生产中

const svgs = getSvgsDependenciesByEntrypoint('app-a');
console.log(svgs) // ["svg1.svg"]

在生产版本中找不到嵌套依赖项

4

1 回答 1

2

我与 webpack 团队一起修复了问题#12202的错误。

此行为与模块的副作用有关。webpack 版本v5.10.3包含一个修复程序,允许手动指定模块具有副作用。您可以在模块规则中或直接在加载器中执行此操作。

于 2021-01-07T15:46:24.917 回答