首页 > 解决方案 > 如何通过 webpack 5 从路径导入 img?

问题描述

我知道这听起来很荒谬,但是是的,我不知道如何使用 webpack 5 导入 img。我想要做的只是导入一个位于项目文件夹中的 img,我想将它导入我的一个反应功能组件,然后将其绘制在<canvas>组件上。

我目前webpack.config.js的情况如下:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const outputDirectory = 'dist';

module.exports = {
    entry: ['babel-polyfill', './src/client/index.js'],
    output: {
        path: path.join(__dirname, outputDirectory),
        filename: 'bundle.js'
    },
    module: {
        rules: [{
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: [
                        "@babel/preset-env",
                        ["@babel/preset-react", {"runtime": "automatic"}]
                    ]
                }
            }
        }, {
            test: /\.css$/i,
            use: [
                MiniCssExtractPlugin.loader,
                'css-loader'
            ]
        }, {
            test: /\.(png|woff|woff2|eot|ttf|svg)$/,
            use: [{
                loader: "url-loader",
                options: {
                    limit: 100000
                }
            }, {
                loader: "css-loader",
                options: {
                    sourceMap: true
                }
            }]
        }]
    },
    resolve: {
        extensions: ['*', '.js', '.jsx']
    },
    devServer: {
        port: 3000,
        open: true,
        historyApiFallback: true,
        hot: true,
        host: '0.0.0.0',
        headers: {"Access-Control-Allow-Origin": "*"},
        proxy: {
            '/api': 'http://localhost:8080'
        }
    },
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            template: './public/index.html'
        }),
        new MiniCssExtractPlugin({
            filename: "./css/[name].css"
        })
    ]
};

我得到的错误信息:

ERROR in ./public/floors.png 1:0
[1] Module parse failed: Unexpected character '�' (1:0)
[1] 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
[1] (Source code omitted for this binary file)
[1]  @ ./src/client/app/pages/WorkspaceGenerator.js 19:0-48 98:15-18
[1]  @ ./src/client/app/App.js 19:0-60 66:42-60
[1]  @ ./src/client/index.js 2:0-28 4:35-38
[1] 
[1] webpack 5.38.1 compiled with 1 error in 589 ms
[1] ℹ 「wdm」: Failed to compile.

我正在处理的项目的层次结构:

在此处输入图像描述

但你知道吗?我真的不知道从哪里开始找到资源来做到这一点,他们的网站上有太多东西是以非人类可读的方式编写的!请帮忙!

标签: reactjswebpack

解决方案


问题

您已将资产css-loader作为一项use规则包含在内png|woff|woff2|eot|ttf|svg,但css-loader不处理图像资产。请删除它作为该特定的规则,test并且仅使用url-loaderfile-loader

解决方案

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const outputDirectory = "dist";

module.exports = {
  entry: ["babel-polyfill", "./src/client/index.js"],
  output: {
    path: path.join(__dirname, outputDirectory),
    filename: "bundle.js",
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: [
              "@babel/preset-env",
              ["@babel/preset-react", { runtime: "automatic" }],
            ],
          },
        },
      },
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
      {
        test: /\.(png|woff|woff2|eot|ttf|svg)$/,
        use: [
          {
            loader: "url-loader", // "file-loader"
            options: {
              limit: 100000,
            },
          },
        ],
      },
    ],
  },
  resolve: {
    extensions: ["*", ".js", ".jsx"],
  },
  devServer: {
    port: 3000,
    open: true,
    historyApiFallback: true,
    hot: true,
    host: "0.0.0.0",
    headers: { "Access-Control-Allow-Origin": "*" },
    proxy: {
      "/api": "http://localhost:8080",
    },
    disableHostCheck: true,
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: "./public/index.html",
    }),
    new MiniCssExtractPlugin({
      filename: "./css/[name].css",
    }),
  ],
};

结果

在此处输入图像描述


推荐阅读