Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
697 views
in Technique[技术] by (71.8m points)

reactjs - Webpack & Typescript image import

I'm working on a React application and using Webpack & Typescript. I would like to use an image in one of the <img/> tags. However, I did not find the proper way to have access to the image files.

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"/>
}

When running the app, the assets/logo-large.png resource is not found.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Alternatively, in your custom_typings folder (if you have that), you can add a new import-png.d.ts file:

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). 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';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...