gpt4 book ai didi

javascript - Webpack 4 文件加载器将 svg 文件内容更改为 __webpack_public_path__

转载 作者:行者123 更新时间:2023-12-04 10:44:39 26 4
gpt4 key购买 nike

我有一个使用 Webpack 4 的项目。我使用文件加载器来处理 html 中的图像和样式中的字体。但是对于图像,file-loader 在 dist 文件夹中创建图像,但将 "module.exports = __webpack_public_path__ + "assets/fonts/main-logo.svg";"串在里面。所以我可以在 html 中看到正确的路径,但我看不到图像。这是我的 webpack 文件:

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"
}
}
}
]
}
}

这是 webpack.dev.js 开发环境文件。
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"]
}
]
}
});

最佳答案

您正在测试带有 .svg 的文件使用相同的加载器扩展两个规则。
如果您打算将 SVG 输出到 assets/fonts您应该从图像文件测试中删除扩展名:

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"
}
}
}
]
}
}

否则,如果您想将 SVG 输出到 assets/images ,您应该从字体测试中删除扩展名:

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"
}
}
}
]
}
}

关于javascript - Webpack 4 文件加载器将 svg 文件内容更改为 __webpack_public_path__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59766230/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com