简体   繁体   English

Webpack & Typescript 图片导入

[英]Webpack & Typescript image import

I'm working on a React application and using Webpack & Typescript .我正在开发React应用程序并使用Webpack & Typescript I would like to use an image in one of the <img/> tags.我想在其中一个<img/>标签中使用图像。 However, I did not find the proper way to have access to the image files.但是,我没有找到访问图像文件的正确方法。

webpack.config.js : webpack.config.js

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

app.tsx :应用程序.tsx

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

When running the app, the assets/logo-large.png resource is not found.运行应用程序时, assets/logo-large.png资源。

Alternatively, in your custom_typings folder (if you have that), you can add a new import-png.d.ts file:或者,在您的 custom_typings 文件夹中(如果有的话),您可以添加一个新的import-png.d.ts文件:

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

So you can import an image using:因此,您可以使用以下方式导入图像:

import myImg from 'img/myImg.png';

Alternatively, as reported by @mario-petrovic, you sometimes need to use a different export option as below (export = syntax).或者,正如@mario-petrovic 所报告的那样,您有时需要使用如下不同的导出选项(export = syntax)。 See here for the differences between the two approaches:请参阅此处了解两种方法之间的区别:

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

In which case you probably need to import the image as:在这种情况下,您可能需要将图像导入为:

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

Setup Webpack file-loader, add declaration.d.ts, and voila!设置 Webpack 文件加载器,添加 declaration.d.ts,瞧!

after spending some time to figure out the solution, this is what I did...花了一些时间找出解决方案后,这就是我所做的......

Step 1步骤1

ensure that you have installed file-loader as a dev dependency by确保您已将file-loader安装为开发依赖项

npm install -D file-loader , if you use yarn yarn add -D file-loader npm install -D file-loader ,如果你使用 yarn yarn add -D file-loader

Step 2第2步

add the loader corresponding to the file extension in the Webpack rules webpack.config.js , like this在webpack规则中添加文件扩展名对应的loader webpack.config.js ,像这样

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

Step 3步骤 3

create an index.d.ts file next to your tsconfig.json file, actually you can name it whatever you want but you have to follow step 4.index.d.ts tsconfig.json ,实际上你可以随意命名它,但你必须按照第 4 步操作。

Since Webpack now is going to handle several image extensions so you can add other image formats supported by file-loader由于 Webpack 现在要处理多个图像扩展,因此您可以添加文件加载器支持的其他图像格式

declare module '*.png';
declare module '*.jpg';

Step 4第4步

go to your tsconfig.json file and add index.d.ts to the include array like this:转到您的tsconfig.json文件并将index.d.ts添加到 include 数组,如下所示:

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

be aware that if you haven't defined an include array, typescript by default is going to add all the files on the root folder, if you just define one file and not the file that contains all your code it is not going to compile.请注意,如果您没有定义一个include数组,默认情况下 typescript 将添加根文件夹中的所有文件,如果您只定义一个文件而不是包含所有代码的文件,它将不会编译。 I think is a good practice to have all your code within the src folder.我认为将所有代码都放在 src 文件夹中是一个好习惯。

Voila!!瞧!

You need to require the image and then use that variable as the source, like so: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"/>
}

For Webpack 5 , there are built-in Assets Modules that replace the old loaders.对于Webpack 5 ,有内置的Assets Modules来替换旧的加载器。

If you're upgrading, make sure you aren't loading assets twice.如果您要升级,请确保您没有加载资产两次。 If you are you can set the Assets Module type to javascript/auto , like so:如果你是,你可以将资产模块类型设置为javascript/auto ,如下所示:

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

If you are starting with a fresh webpack config, there's no longer a need to install any of the loaders, nor use them in the config.如果您从全新的 webpack 配置开始,则不再需要安装任何加载程序,也无需在配置中使用它们。 Simply follow the steps mentioned by @Carlos, skipping step #1 and replacing the code in step #2 with the following:只需按照@Carlos 提到的步骤,跳过步骤 #1 并将步骤 #2 中的代码替换为以下代码:

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

The copy-webpack-plugin might solve your problem as well, when you have a lot of images you can just serve them all from one central dist folder. copy-webpack-plugin也可以解决你的问题,当你有很多图像时,你可以从一个中央dist文件夹中为它们提供所有服务。

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

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

No you can simply at the relative path to your image tag:不,您可以简单地使用图像标签的相对路径:

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

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

Actually, you do not require webpack for using webp images.实际上,您不需要 webpack 来使用webp图像。 This solution works for TypeScript and JavaScript based react apps as well.该解决方案也适用于基于TypeScriptJavaScript的 React 应用程序。 TypeScript gives an error if you try to import webp image as ReactComponent .如果您尝试将webp图像导入为ReactComponent ,TypeScript 会报错。 So you should not import it as a component, but use only the source of image.所以你不应该将它作为一个组件导入,而应该只使用图像的来源。 Check this example:检查这个例子:

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

Now you can use this src in your现在你可以在你的tag like this.像这样标记。

<img src={img} />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM