2

I am having an issue where I am getting the following error when using webpack to load my image files. If I run the application with the webpack-dev-server, the image will display so it is able to pull it in.

enter image description here

The folder structure looks like so:

- home
   -home.tsx
-images
   -test2.png

This is the webpack config file where I am trying to modularize the images to be used with imports:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')

const config = {
  entry: './src/index.tsx',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      },
      {
        test: /\.less$/,
        use: [
          {
            loader: "style-loader"
          },
          {
            loader: "css-loader"
          },
          {
            loader: "less-loader"
          }
        ]
      },
      { 
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use:'url-loader' 
      },
      { 
        test: /\.(png|jp(e*)g|svg)$/,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 10000,
              name: 'images/[hash]-[name].[ext]',
            },
          }
        ]
      }
    ]
  },
  resolve: {
    extensions: [ '.ts', '.tsx', '.js' ]
  },
  plugins: [
    new HtmlWebpackPlugin({
        title: 'Application Name',
        template: path.join(__dirname, 'src/index.html')
    })
  ],
  devtool: 'inline-source-map',
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    historyApiFallback: true,
    compress: true,
    port: 8080
  }
};

module.exports = config;
Shawn
  • 2,355
  • 14
  • 48
  • 98
  • This post ended up helping me if anybody else runs into this issue with css/images in typescript. https://stackoverflow.com/questions/45432951/typescript-compiler-cannot-find-module-when-using-webpack-require-for-css-imag – Shawn Mar 30 '18 at 04:54

2 Answers2

3

You can try with

const testImage = require('../images/test2.png');

Because image is not module. So you can't import this.

EDIT(by Shawn)

we can export image file with declare module '*.png' See the post in github

Tan Duong
  • 2,124
  • 1
  • 11
  • 17
  • Niiice ya I just came across this also and it is working fine. Wanting to see if I can find a way to leave it as an import. Apparently if you create a file with ```declare module '*.png'``` it will allow you to use the import also. Continuing to look for a cleaner way – Shawn Mar 30 '18 at 04:52
  • 1
    You as well! Left a comment to my question pointing to another post that explains this a little better – Shawn Mar 30 '18 at 05:03
0

You can try

<img src= "./images/test2/png>"

it worked for me

meBe
  • 154
  • 9