导入SVG图像会导致警告:Prop`src`不匹配。服务器:

时间:2020-07-17 16:28:01

标签: reactjs webpack next.js

我在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-book-reading.svg”客户端: “ /_next/images/364068d183bb962a8423031f65bab6ad-book-reading.svg”

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您需要将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的开头添加它。

Source