Webpack 和 Typescript 图像导入

问题描述 投票:0回答:7

我正在开发 React 应用程序并使用 WebpackTypescript。我想在

<img/>
标签之一中使用图像。但是,我没有找到访问图像文件的正确方法。

webpack.config.js:

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

app.tsx

...
render() {
    return <img src='/assets/logo-large.png' alt="logo"/>
}

运行应用程序时,找不到

assets/logo-large.png
资源。

reactjs typescript webpack
7个回答
72
投票

或者,在您的 custom_typings 文件夹中(如果有的话),您可以添加一个新的

import-png.d.ts
文件:

declare module "*.png" {
  const value: any;
  export default value;
}

因此您可以使用以下方式导入图像:

import myImg from 'img/myImg.png';

或者,正如 @mario-petrovic 所报告的,您有时需要使用不同的导出选项,如下所示(export = 语法)。请参阅此处了解两种方法之间的差异:

declare module "*.png" {
  const value: any;
  export = value;
}

在这种情况下,您可能需要将图像导入为:

import * as myImg from 'img/myImg.png';

48
投票

设置 Webpack 文件加载器,添加声明.d.ts,瞧!

花了一些时间找出解决方案后,这就是我所做的......

步骤1

确保您已安装

file-loader
作为开发依赖项

npm install -D file-loader
,如果你使用纱线
yarn add -D file-loader

步骤2

在Webpack规则中添加文件扩展名对应的loader

webpack.config.js
,像这样

module: {
    rules: [
      ...,
      {
        test: /\.(png|jpe?g|gif|jp2|webp)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
        },
      },
    ],
  },

步骤3

在您的

index.d.ts
文件旁边创建一个
tsconfig.json
文件,实际上您可以将其命名为任何您想要的名称,但必须遵循步骤 4。

由于 Webpack 现在将处理多种图像扩展,因此您可以添加 file-loader

支持的其他图像格式
declare module '*.png';
declare module '*.jpg';

步骤4

转到您的

tsconfig.json
文件并将
index.d.ts
添加到包含数组中,如下所示:

{
  "compilerOptions": {
    ...,
    "jsx": "react",
    "esModuleInterop": true,
    "target": "ES2020",
    "moduleResolution": "node"
  },
  "exclude": ["node_modules", "**/*.spec.ts", "**/*.test.ts"],
  "include": ["src", "index.d.ts"] /// <-- Like this!!
}

请注意,如果您还没有定义

include
数组,默认情况下,打字稿将添加根文件夹中的所有文件,如果您只定义一个文件而不是包含所有代码的文件,则打字稿不会添加来编译。我认为将所有代码放在 src 文件夹中是一个很好的做法。

瞧!!


24
投票

您需要

require
图像,然后使用该变量作为源,如下所示:

// At the top of the file, with all other imports/requires
const imageSrc = require('/assets/logo-large.png')

...

render() {
    return <img src={String(imageSrc)} alt="logo"/>
}

5
投票

对于 Webpack 5,有内置的

Assets Modules
替代了旧的加载器。

如果您要升级,请确保您没有加载资源两次。如果是的话,您可以将资产模块类型设置为

javascript/auto
,如下所示:

{
  test: /\.(png|jpg|gif)$/i,
  use: [
     {
       loader: 'url-loader',
       options: {
         limit: 8192,
       }
     },
   ],
   type: 'javascript/auto'
}

如果您从新的 webpack 配置开始,则不再需要安装任何加载器,也不再需要在配置中使用它们。只需按照@Carlos提到的步骤操作,跳过步骤#1并将步骤#2中的代码替换为以下内容:

rules: [ 
  {
    test: /\.(png|jpe?g|gif|jp2|webp)$/,
    type: 'asset/resource'
  },
//further sexiness
]

1
投票

copy-webpack-plugin
也可以解决您的问题,当您有大量图像时,您可以从一个中央
dist
文件夹中提供所有图像。

npm install --save-dev copy-webpack-plugin

    plugins: [
        ...
        ...
        new CopyWebpackPlugin([
            {from:'src/images',to:'images'} 
        ]), 
    ...
    ]

不,您可以简单地访问图像标签的相对路径:

<img src='images/your-image.png' />

来源:https://medium.com/a-beginners-guide-for-webpack-2/copy-all-images-files-to-a-folder-using-copy-webpack-plugin-7c8cf2de7676


0
投票

你可以尝试 webpack 魔法注释

 import(
  /* webpackMode: "lazy-once" */
  /* webpackChunkName: "i18n-extra" */
  `@/../node_modules/src/assets/icons/${this.name}.svg`)

-1
投票

实际上,您不需要 webpack 来使用 webp 图像。该解决方案也适用于基于 TypeScriptJavaScript 的 React 应用程序。如果您尝试将 webp 图像导入为 ReactComponent,TypeScript 会出错。因此,您不应将其作为组件导入,而应仅使用图像源。检查这个例子:

import img from "./images/image.webp";

现在您可以像这样在 标签中使用此 src。

<img src={img} />
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.