首页 > 解决方案 > Webpack React 构建后对图像的模糊引用

问题描述

我正在使用 webpack 构建我的应用程序,到目前为止它越来越好。我的模块似乎都没有损坏。旁白:我只是怀疑,因为我对这个东西如何将我的 150mb React 应用程序变成 2mbs 感到非常困惑,并且几乎不知道这东西是如何工作的。

我遇到的问题是我的图像或大部分 CSS 都没有正确加载。这是一个示例元素

<img class="searched-user-icon bump-icon" src="export default __webpack_public_path__ + &amp;quot;src/static/pointingfinger.svg&amp;quot;;" alt="pointingfinger">

这不会渲染图像。它给了我一个 404。现在,如果我在浏览器开发工具中将其更改为此:

<img class="searched-user-icon bump-icon" src="src/static/pointingfinger.svg" alt="pointingfinger">

它有效,这是有道理的。但当然我需要解决这个问题,以便图像在构建后正常显示。我在我的反应组件文件中导入我的图像:import pointingfinger from '../static/pointingfinger.svg';

我没有找到很多关于这种奇怪现象的文档。我想知道是否有人知道可以向我解释发生了什么,这将不胜感激。此外,我想简单地复制我的 css,基于在构建期间相对地找到 css 文件的位置,就像我对文件加载器所做的那样。我可以手动设置它以将它找到的所有 css 放入一个文件夹中,但这似乎不太“动态”。下面是我的 webpack 配置

module.exports = {
    entry: "./src/index.js", // The entry point for the application
    output: {
        path: path.join(__dirname, '/dist'),
        publicPath: '/',
        filename: 'index_bundle.js' // This will be the created bundle file that webpack creates for react to use in production
    },
    module: {
        rules: [
            { 
                test: /\.jsx?$/, 
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            },
            {
                test: /\.svg$/, use: 'svg-inline-loader'
            },
            {
                test: /\.css$/i, use: [ 'style-loader', 'css-loader' ]
            },
            {
                test: /\.(png|jpe?g|gif|svg)$/i, loader: 'file-loader', options: { name: '[path][name].[ext]' }
            }
        ]
    },
    target: ['web', 'es5'],
    plugins: [
        new HtmlWebpackPlugin({ template: './public/index.html'}),
        new webpack.ProvidePlugin({
            process: 'process/browser'
        })
    ],
    mode: 'production' // Can be set to development or production. Webpack will minify code and strip warnings
}

编辑:看起来配置<img src={pointingfinger}></img>在我的代码中引用这样的源时出现问题。我打赌一个简单的插件就足够了。当我发现一些东西时,我会更新。

edit2:使用插件“plugin-transform-react-jsx”似乎不能解决这个问题。

标签: cssreactjswebpackbabeljs

解决方案


我通过删除解决了这个问题

{
   test: /\.svg$/, use: 'svg-inline-loader'
}

虽然许多其他教程都说要使用它,但我的 React 应用程序主要将它们用作 img 和 src 对它们的引用。它们大多是在组件的顶部导入import theimgvar from 'a/path/to/img.svg';并像这样引用src={theimgvar}

所以只需要定义文件加载器来加载 svg 以及我已经在那里

{
   test: /\.(png|jpe?g|gif|svg)$/i,
   loader: 'file-loader', 
   options: { name: '[path][name].[ext]' }
}

推荐阅读