如何防止在 webpack 中生成散列损坏的资产(图像文件)?

2024-04-14

伙计们,您是否在 Web Pack 中想到过在图像输出中设置特定路径,但在输出中创建的文件是输出文件夹根目录中的损坏文件(此处为 dist)? 虽然健康文件已创建但未链接。 在 html 中,css 链接损坏的文件

或者让我这样说:

我想要创建的输出:

src
webpack/webpack.config.js
dist
|—— |fonts
|—— |js
|—— |img
-————--img1.jpg
-————--img2.png
———-—--img3.png
——- index.html
——- another.html

但最终输出:

src
webpack/webpack.config.js
dist
|—— |fonts
|—— |js
|—— |img
-————--img1.jpg
-————--img2.png
-————--img3.png
——- index.html
——- another.html
——- sdf8s7s.jpg => broken and linked file
——- sdf8ws3.png => broken and linked file
——- sd4sg7i.png => broken and linked file

.

//webpack/webpack.config.js

module.exports = {
    entry: {
        'bundle': path.resolve(__dirname, '../src/js/index.js'),
    },
    output: {
        path: path.resolve(__dirname, "../dist"),
        filename: "js/[name].js",
        clean: true,
    },
    module: {
        rules: [
            //...
            {
                test: /\.(png|svg|jp[e]g|gif|webp)$/i,
                loader: 'file-loader',
                options: {
                    outputPath: '/img/',
                    name: "[name].[ext]",
                    useRelativePaths: true,
                    publicPath: '../img/'
                },
            },
            //...
        ],
    },
    plugins: [
        //...
    ],
};

如果您仔细观察并尝试在文本编辑器中打开这些图像,您就会明白到底发生了什么。 无论如何,在新的 webpack 中,不需要图像文件加载器,如文档中所示。

我为解决这个问题所做的是将其添加到 webpack 配置中:

module.rules[{
  test: /\.(png|svg|jpg|jpeg|gif)$/i,
  type: "asset/resource"
}]

and

output: {assetModuleFilename: 'images/[name][ext]'}

这应该修复链接、损坏的图像和散列

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何防止在 webpack 中生成散列损坏的资产(图像文件)? 的相关文章

随机推荐