我在webpack工作流程中使用SVG遇到了很多麻烦。我试图用CSS中的background: url(sample.svg)
属性来显示它。单独使用它不起作用,所以我认为我使用了装载机。以下是我使用的步骤。
我使用svg-url-loader加载SVG。
1.我通过npm安装了svg-url-loader
并将其添加到我的module.exports
:
{
test: /\.svg/,
use: {
loader: 'svg-url-loader'
}
},
2.我将它添加到index.js文件的顶部:
require('svg-url-loader!./images/topography.svg');
3.我将background-image
添加到我的CSS的SVG路径:
body {
background-image: url("../images/topography.svg");
background-size: 340px, auto;
min-height: calc(100vh - 100px);
margin: 50px;
background-attachment: fixed;
letter-spacing: -1px;
}
4. SVG未呈现到页面。当我在浏览器中检查身体时,我发现:
background: url(data:image/svg+xml,module.exports = __webpack_public_path__ + '8dccca4….svg';);
我不太了解data-uri,所以也许我在那里遇到了问题。
此外,我尝试使用不同的SVG文件,但没有一个工作。
我遇到了同样的错误。经过一些调查,我发现我添加了另一个导致这个问题的svg
加载器,所以我通过删除其他svg
加载器修复它:
{
test: /\.svg/,
use: {
loader: 'svg-url-loader'
}
},
{
test: /\.svg$/,
use: [
"babel-loader",
{
loader: "react-svg-loader",
options: {
svgo: {
plugins: [{ removeTitle: false }],
floatPrecision: 2
},
jsx: true
}
}
]
}
所以你也可以添加一些额外的加载器来同时处理svg
文件,请检查。
您可以:
a)在webpack.config.js中设置加载器:
example.js:
import ExampleIcon from 'assets/icons/example-icon.svg';
...
<ExampleIcon className={styles.exampleIcon} />
webpack.config.js:
{
test: /\.svg$/,
use: [
{
loader: 'babel-loader',
},
{
loader: 'react-svg-loader',
options: {
svgo: {
plugins: [{ removeTitle: false }],
floatPrecision: 2
},
jsx: true
}
}
]
},
b)或在导入字符串中设置加载器:
import ExampleIcon from '!babel-loader!react-svg-loader!assets/icons/example-icon.svg';
...
<ExampleIcon className={styles.exampleIcon} />