问题
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.
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;
回答1:
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
来源:https://stackoverflow.com/questions/49568377/imports-not-recognizing-image-modules-in-react-using-webpack-with-typescript