首页 > 解决方案 > Webpack 在 React 图像导入时抛出错误

问题描述

我正在尝试使用 React (create-react-app) 和 Firebase 实现 SSR。为此,我目前正在webpack按照本教程github dir进行配置:

module.exports = [{
    entry: './src/index.js',
    module: {
        rules: [
            {test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/},
            {test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/},
            {test: /\.css$/i, use: ['style-loader', 'css-loader']},
        ]
    },
    output: {
        filename: 'public/bundle.js',
        path: __dirname
    }
}];

我有一个包含一些图像的资产文件夹。不知何故,对于所有导入,webpack返回以下错误:

ERROR in ./src/assets/images/capture_5_move_on/1.JPG 1:0
    Module parse failed: Unexpected character '�' (1:0)
    You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
    (Source code omitted for this binary file)
     @ ./src/shared/data.js 28:0-59 78:9-12
     @ ./src/modules/CartHolder/CartHolderMobile.js
     @ ./src/App.js
     @ ./src/index.js

标签: reactjswebpack

解决方案


您应该为图像使用文件加载器:https ://github.com/webpack-contrib/file-loader 。

不知何故像这样:

module.exports = [{
    entry: './src/index.js',
    module: {
        rules: [
            {test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/},
            {test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/},
            {test: /\.(png|jpe?g|gif)$/i, loader: 'file-loader', exclude: /node_modules/},
            {test: /\.css$/i, use: ['style-loader', 'css-loader']},
        ]
    },
    output: {
        filename: 'public/bundle.js',
        path: __dirname
    }
}];

推荐阅读