我想使用react-svg-loader导入并使用我的应用拥有的一些svg资产。您可以在下面找到我的webpack配置。但是,问题是我还在为svg文件使用一些文件加载器。这些是必需的,因为我的应用程序的某些部分正在从真棒字体(例如<i className="fa fa-lock" aria-hidden="true" />
。因此,我可以通过停止让文件加载器查找svg文件来使react-svg-loader正常工作,但是我的应用程序上的许多图标都不会呈现。如果我不这样做,那么我的webpack将无法构建,并显示以下内容:
ERROR in ./node_modules/font-awesome/scss/font-awesome.scss
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/react-svg-loader/lib/loader.js):
NonErrorEmittedError: (Emitted value instead of an instance of Error) Error in parsing SVG: Non-whitespace before first tag.
那么我该如何解决这两个冲突?谢谢。
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const DIST_DIR = path.resolve(__dirname, "dist");
const SRC_DIR = path.resolve(__dirname, "src");
const config = {
entry: [
"babel-polyfill",
`${SRC_DIR}/app/index.js`,
`${SRC_DIR}/app/assets/stylesheets/application.scss`,
`${SRC_DIR}/app/components/index.scss`,
"font-awesome/scss/font-awesome.scss",
"react-datepicker/dist/react-datepicker.css",
"rc-time-picker/assets/index.css",
"react-circular-progressbar/dist/styles.css",
"@trendmicro/react-toggle-switch/dist/react-toggle-switch.css",
],
output: {
path: `${DIST_DIR}/app/`,
filename: "bundle.js",
publicPath: "/app/"
},
module: {
rules: [
{
test: /\.svg$/,
use: [
{
loader: "babel-loader"
},
{
loader: "react-svg-loader",
options: {
jsx: true
}
}
]
},
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
failOnWarning: false,
failOnError: true
}
},
{
test: /\.js$/,
include: SRC_DIR,
loader: 'babel-loader',
query: {
presets: ['react', 'stage-2']
}
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: ['file-loader?context=src/images&name=images/[path][name].[ext]', {
loader: 'image-webpack-loader',
query: {
mozjpeg: {
progressive: true,
},
gifsicle: {
interlaced: false,
},
optipng: {
optimizationLevel: 7,
},
pngquant: {
quality: '75-90',
speed: 3,
},
},
}],
exclude: path.resolve(__dirname, "node_modules"),
include: __dirname,
},
{
test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
// loader: "url?limit=10000"
use: "url-loader"
},
{
test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
use: 'file-loader'
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "application.css"
}),
]
};
module.exports = config;
答案 0 :(得分:1)
我在尝试使用react-svg-loader加载SVG时遇到了类似的问题,但是在使用file-loader加载Font Awesome SVG时遇到了类似的问题。这是我用来解决该问题的配置:
{
test: /\.svg$/,
exclude: path.resolve(__dirname, 'node_modules', 'font-awesome'),
use: ['babel-loader', 'react-svg-loader'],
},
{
test: /\.svg$/,
include: path.resolve(__dirname, 'node_modules', 'font-awesome'),
use: [{
loader: 'file-loader',
options: {
jsx: true,
},
}],
},
如果您的webpack配置不在根目录中,请相应地更正排除/包含路径!
请注意,您在webpack配置中对SVG有多个规则,请使用包含/排除规则使它们全部适用于您的情况。