简体   繁体   English

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

[英]How to prevent generating hashed broken assets (Image files) in webpack?

Guys has it occurred to you in the web pack to set a specific path in the output for images, but the files that are created in the output are broken files in the root of the output folder (which is dist here)?伙计们,您是否在 web pack 中想到在输出中为图像设置特定路径,但是在输出中创建的文件是输出文件夹根目录中的损坏文件(这里是 dist)? While healthy files are created but not linked.虽然创建了健康文件但未链接。 And in html, css links the broken files在 html 中,css 链接损坏的文件

Or let me put it this way:或者让我这样说:

The output I want to create:我要创建的输出:

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

But the final output :但最终输出:

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: [
        //...
    ],
};

If you look closely and open try to open those images in text editor you'd get what exactly happened.如果您仔细观察并打开尝试在文本编辑器中打开这些图像,您就会知道到底发生了什么。 Anyway in the new webpack there's no need for file loader for images as shown in the docs.无论如何,在新的 webpack 中,不需要像文档中所示的图像文件加载器。

what i've done to solve this problem is to add this to webpack config:我为解决此问题所做的工作是将其添加到 webpack 配置中:

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

and

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

this should fix the linking, broken images, and hashing这应该修复链接、损坏的图像和散列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM