Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
704 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...