导入SVG图像导致警告:道具"src"不匹配.服务器:



我在next.js项目中安装了文件加载器,并将next.config.js配置为这样:

module.exports = {
entry: './src/index.js',
webpack: config => {
const env = Object.keys(process.env).reduce((acc, curr) => {
acc[`process.env.${curr}`] = JSON.stringify(process.env[curr]);
return acc;
}, {});
config.plugins.push(new webpack.DefinePlugin(env));
config.module.rules.push({
test: /.(png|jp(e*)g|svg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'images/[hash]-[name].[ext]',
},
},
],
});
return config;
}
};

然后我在/public/images/book-reading.svg中有一个图像

所以我试着在/src/components:中的一个组件中导入这样的图像

import BookReading from '../../public/images/book-reading.svg';

像这样使用它:

<img src={BookReading} />

然而,图像没有显示,我得到了这个警告:

警告:道具src不匹配。服务器:"images/364068d183bb962a8423031f65bab6ad图书阅读;客户:"_next/images/364068d183bb962a8423031f65bab6ad图书阅读;

有什么想法吗?

您需要将publicPathoutputPath添加到文件加载器的选项中。

module.exports = {
webpack: config => {
config.module.rules.push({
test: /.(png|jp(e*)g|svg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'images/[hash]-[name].[ext]',
publicPath: `/_next/static/images/`,
outputPath: 'static/images',
},
},
],
});
return config;
}
};

这不是您的情况,但为了完整性:如果您使用了不同的basePath,则需要在publicPath的开头添加它。

最新更新