Webpack & Typescript image import

后端 未结 3 642
醉话见心
醉话见心 2020-12-09 01:20

I\'m working on a React application and using Webpack & Typescript. I would like to use an image in one of the &

相关标签:
3条回答
  • 2020-12-09 01:55

    You need to require the image and then use that variable as the source, like so:

    // 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"/>
    }
    
    0 讨论(0)
  • 2020-12-09 01:55

    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.

    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

    0 讨论(0)
  • 2020-12-09 02:08

    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';
    
    0 讨论(0)
提交回复
热议问题