'Webpack 4 file-loader changes svg file content to __webpack_public_path__
I have a project that uses Webpack 4. I use file-loader to handle images in html and fonts in the styles. But for the images, file-loader creates the image in dist folder but puts "module.exports = __webpack_public_path__ + "assets/fonts/main-logo.svg";" string in it. So i can see the correct path in the html but i can't see the image. Here is my webpack file:
webpack.common.js
const path = require('path');
module.exports = {
entry: "./src/index.js",
module: {
rules: [
{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.(svg|png|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
esModule: false,
name: "[name].[ext]",
outputPath: "assets/images"
}
}
},
{
test: /\.(woff(2)?|ttf|eot|svg)([\?]?.*)?$/,
exclude: /node_modules/,
use: {
loader: "file-loader",
options: {
esModule: false,
name: "[name].[ext]",
outputPath: "assets/fonts"
}
}
}
]
}
}
And this is the webpack.dev.js file for development env.
const common = require('./webpack.common');
const merge = require('webpack-merge');
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
module.exports = merge(common, {
mode: "development",
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist")
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/template.html"
})
],
module: {
rules: [
{
test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader"]
}
]
}
});
Solution 1:[1]
You are testing for files with .svg
extension in two rules with the same loader.
If your intention is to output SVGs to assets/fonts
you should remove the extension from the image files test:
const path = require('path');
module.exports = {
entry: "./src/index.js",
module: {
rules: [
{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.(png|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
esModule: false,
name: "[name].[ext]",
outputPath: "assets/images"
}
}
},
{
test: /\.(woff(2)?|ttf|eot|svg)([\?]?.*)?$/,
exclude: /node_modules/,
use: {
loader: "file-loader",
options: {
esModule: false,
name: "[name].[ext]",
outputPath: "assets/fonts"
}
}
}
]
}
}
Otherwise, if you want to output SVGs to assets/images
, you should remove the extension from the fonts test:
const path = require('path');
module.exports = {
entry: "./src/index.js",
module: {
rules: [
{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.(svg|png|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
esModule: false,
name: "[name].[ext]",
outputPath: "assets/images"
}
}
},
{
test: /\.(woff(2)?|ttf|eot)([\?]?.*)?$/,
exclude: /node_modules/,
use: {
loader: "file-loader",
options: {
esModule: false,
name: "[name].[ext]",
outputPath: "assets/fonts"
}
}
}
]
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | bamb0ocha |