首页 > 解决方案 > 如何加载图像反应 babel

问题描述

我正在我的 app.js 上加载图标

import bg from './icons/bg.png';
import br from './icons/br.png';
import rg from './icons/rg.png';
import ig from './icons/invert.png';
import bw from './icons/bw.png';
import by from './icons/by.png';
import gm from './icons/gm.png';
import rs from './icons/rs.png';

当我运行默认的反应启动脚本时它们工作正常,但是当我尝试使用这个 webpack 编译时:

const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/js/index.js',
  devtool: 'inline-source-map',
  target: 'electron-renderer',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [[
              '@babel/preset-env', {
                targets: {
                  esmodules: true
                }
              }],
              '@babel/preset-react']
          }
        }
      },
      {
        test: [/\.s[ac]ss$/i, /\.css$/i],
        use: [
          // Creates `style` nodes from JS strings
          'style-loader',
          // Translates CSS into CommonJS
          'css-loader',
          // Compiles Sass to CSS
          'sass-loader',
        ],
      }
    ]
  },
  resolve: {
    extensions: ['.js'],
  },
  output: {
    filename: 'app.js',
    path: path.resolve(__dirname, 'build', 'js'),
  },
};

我得到每个图像的这个错误:

ERROR in ./src/js/icons/bg.png 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/js/App.js 2:0-32 230:9-11
 @ ./src/js/index.js 4:0-24 5:107-110

这可证明意味着 babel 正在尝试将图像加载为 javascript 文件,有没有办法在使用 Babel 编译时在 React 上加载图像?

标签: reactjselectronbabeljs

解决方案


如 webpack 文档中所述

开箱即用,webpack 只理解 JavaScript 和 JSON 文件。

所以你需要对 png 文件使用加载器,因为 webpack 不知道如何处理该文件。

文件加载器

更多关于装载机


推荐阅读