导入无法识别图像模块在使用带有typescript的webpack的react中 [英] Imports not recognizing image modules in react using webpack with typescript
问题描述
我遇到一个问题,使用Webpack加载图像文件时出现以下错误.如果我使用webpack-dev-server运行该应用程序,则会显示该图像,以便能够将其拉入.
文件夹结构如下:
- home
-home.tsx
-images
-test2.png
这是webpack配置文件,我试图在其中模块化要与导入一起使用的图像:
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;
您可以尝试
const testImage = require('../images/test2.png');
因为图像不是模块.所以你不能导入它.
编辑(作者肖恩)
我们可以使用declare module '*.png'
导出图像文件
请参阅github中的帖子 >
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;
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
这篇关于导入无法识别图像模块在使用带有typescript的webpack的react中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!