I am trying to load a jpg file on the Homepage of my app:
import cad from './CAD/untitled.106.jpg'
but the following error kept popping up:
assets by status 2 MiB [cached] 1 asset
cached modules 2.41 MiB (javascript) 937 bytes (rjavascript modules 420 KiB
./src/components/HomePage.js 1.18 KiB [built]
./src/components/CAD/untitled.106.jpg 419 KiB [
(1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
@ ./src/components/HomePage.js 7:0-41
@ ./src/components/App.js 3:0-34 12:90-98
@ ./src/index.js 1:0-35
webpack 5.70.0 compiled with 1 error in 84 ms
I have tried modifying the webpack.config.js by adding a rule with 'file-loader'. However, the problem remained. Currently, I am using "webpack": "^5.70.0". Here is my webpack.config.js:
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "./static/frontend"),
filename: "[name].js",
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.(jpeg|png|jpg|svg|gif)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
}
}
],
},
],
},
optimization: {
minimize: true,
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("development"),
},
}),
],
};
I have tried many different approaches and solutions, and I have no idea why my webpack.config.js can not process a jpg file. Can someone tell me the root cause of this problem? Thank you very much.
CodePudding user response:
In webpack 5 you can just load it as asset/resource
asset/resource emits a separate file and exports the URL. Previously achievable by using file-loader.
So it should look like this:
{
test: /\.(?:ico|gif|png|jpg|jpeg|svg)$/i,
type: 'asset/resource',
},