首页 > 解决方案 > Webpack 5 Asset Modules 不捆绑图像

问题描述

我正在尝试使用新的 webpack 5 特性Asset Modules在我的反应库中包含一个静态 png 图像。这应该是一项基本任务,但我正在努力弄清楚为什么不包含图像。我做了以下事情。

  1. 将规则作为webpack.config.js的一部分包含在内
module.exports = {
    entry: './index.ts',
    output: {
        filename: 'index.js',
        path: __dirname,
        assetModuleFilename: 'assets/[hash][ext][query]'
    },
    module: {
        rules: [
          {
            test: /\.png/,
            type: 'asset/resource'
          }
        ]
    },
};
  1. 在组件中导入并使用图像
import React from 'react';
import image from '../src/assets/transport-belt-down.png'

function RenderedSquare(props: RenderedSquareProps){
    return <img src={image}>image</img>
}

export { RenderedSquare };

这个组件是 index.ts 中唯一呈现的东西,因此肯定会使用图像。

但是,当我运行时,图像不会包含在disttsc文件夹中。这意味着在使用库时会出现以下错误。

../factorio-blueprint-renderer/src/assets/transport-belt-down.png
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

我尝试过的事情

标签: reactjstypescriptwebpackassets

解决方案


推荐阅读