我如何从 webpack 5 中的编译中获取按入口点过滤的文件依赖项的平面列表

How can i get a flat list of file dependencies filtered by entry point from the compilation in webpack 5

我正在尝试更新 svg-chunk-webpack-plugin from webpack v4 to v5. The plugin used the compilation 对象,需要一个按入口点筛选的文件依赖项的平面列表,以提取每个入口点的所有 SVG。

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

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

使用 webpack v4,以下代码有效,returns 每个入口点使用的所有 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"]

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

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"]

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

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

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