How to prevent generating hashed broken assets (Image files) in webpack?
Asked Answered
S

1

3

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)? While healthy files are created but not linked. And in html, css links the broken files

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: [
        //...
    ],
};
Symposium answered 24/10, 2021 at 16:10 Comment(0)
E
3

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.

what i've done to solve this problem is to add this to webpack config:

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

Endoergic answered 14/11, 2021 at 14:7 Comment(1)
Thanks a million <3 . Problem solved.Symposium

© 2022 - 2024 — McMap. All rights reserved.