我想加载svg图像,因此我下载了svg-inline-loader。并使用以下示例进行配置:Webpack svg-inline-loader。尝试加载svg文件后,我得到了。不使用webpack svg-inline-loader加载svg文件会给我一个错误。有什么想法可以解决吗?
HTML
<img src="./svg/facebook-square-brands.svg" alt="Facebook"/>
我的Webpack配置文件.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry:{
scripts: "./src/scripts/index.js",
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
}
},
{
test: /\.html$/,
use: [{ loader: "html-loader", options: { minimize: true } }]
},
{
test: /\.(png|jpe?g)/i,
use: [
{
loader: "url-loader",
options: {
name: "./img/[name].[ext]",
limit: 10000
}
},
{
loader: "img-loader",
}
]
},
{
test: /\.svg$/,
use: [
{
loader: 'svg-inline-loader',
}
]
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
"sass-loader"
]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "src/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
};
PackageJson依赖项:
"devDependencies": {
"@babel/core": "^7.2.0",
"@babel/preset-env": "^7.2.0",
"@babel/preset-react": "^7.0.0",
"autoprefixer": "^9.4.1",
"babel-loader": "^8.0.4",
"css-loader": "^1.0.1",
"file-loader": "^2.0.0",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"img-loader": "^3.0.1",
"mini-css-extract-plugin": "^0.4.5",
"node-sass": "^4.10.0",
"postcss-loader": "^3.0.0",
"sass-loader": "^7.1.0",
"svg-inline-loader": "^0.8.0",
"url-loader": "^1.1.2",
"webpack": "^4.26.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.14"
},
答案 0 :(得分:2)
我知道问题提出已经一年多了,但我为将来登陆这里的人添加了答案。
假设 svg-inline-loader
用于将svg inline用作其自身注入的文件。您想要完成的工作最好是使用url-loader
或svg-url-loader
(https://www.npmjs.com/package/svg-url-loader)将svg转换为base64,以便可以在src属性中使用它。
如果您想同时使用它们,可以将其与以下oneOf配置结合使用:
{
test: /\.svg$/,
oneOf: [
{
include: path.resolve(__dirname, '../node_modules/package-name/'),
use: 'svg-inline-loader'
},
{
exclude: path.resolve(__dirname, '../node_modules/package-name/'),
use: 'url-loader'
}
]
}