I'm trying to output all image files through webpack file loader, webpack is ignoring images with PNG extensions however. Configuration works correctly on JPG files.
My webpack config:
const path = require('path');
const PATHS = {
src: path.join(__dirname, 'src'),
img: path.join(__dirname, 'src/img'),
styles: path.join(__dirname, 'src/styles'),
build: path.join(__dirname, 'build')
}
module.exports = {
context: PATHS.src,
entry: {
script: ['./scripts/main.js', './styles/main.scss'],
index: './index.html'
},
output: {
path: PATHS.build,
filename: '[name].js'
},
module: {
loaders: [{
test: /\.scss$/,
loaders: ["style", "css", "sass"],
include: PATHS.styles
}, {
test: /\.(png|jpg)$/i,
loader: 'file?name=[path][name].[ext]',
include: PATHS.img
}, {
test: /\.(html)$/,
loader: 'file?name=[path][name].[ext]'
}]
}
};
source folder structure
Use with url-loader or file-loaderurl-loader and file-loader are deprecated over Asset Modules in webpack v5.
First, put your image files into one folder of your projects application. For instance, your src/ folder may have a folder assets/ which has a folder images/. }; It's quite similar to setting up fonts with Webpack.
Referencing to images Webpack can pick up images from style sheets through @import and url() assuming css-loader has been configured. You can also refer to your images within the code. In this case, you have to import the files explicitly: import src from "./avatar.
Webpack goes through all the import ed and require d files in your project, and for all those files which have a . svg extension, it uses as an input to the webpack file loader. For each of these files, the file loader emits the file in the output directory and resolves the correct URL to be referenced.
The problem with the PNG files was with importing PNG images, both were imported by html src attribute, while JPG image was imported by url attribute in css. Therefore the problem was not in the image formats.
Fixed by adding extract-loader and html-loader to html loader. Webpack then matches even src attributes in html if i understand it correctly.
Html loader configuration:
loader: 'file-loader?name=[path][name].[ext]!extract-loader!html-loader'
Thanks for pointing me out about the image importing method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With