[英]Cannot find module in react component
當我嘗試將圖像放入反應組件時,我看到Cannot find module '../../assets/images/logo.png' or its corresponding type declarations.
. 我添加了declare module *.png
in.d.ts 文件,但它仍然無法正常工作。 我從 webapack 開始,所以我的問題可能非常愚蠢,但我真的需要幫助。 當我從 tsconfig 中刪除"include": ["src/**/*"]
時,一切正常。 有什么問題?
Webpack:
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
const ErrorOverlayPlugin = require('error-overlay-webpack-plugin')
module.exports = {
entry: '/src/index.tsx',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
resolve: {
extensions: [".ts", ".tsx", ".js"]
},
devtool: 'cheap-module-source-map',
module: {
rules: [
{
test: /\.tsx?/,
loader: 'ts-loader'
},
{
test: /\.js/,
exclude: (/node_modules/),
loader: 'babel-loader'
},
{
test: /\.s[ac]ss$/i,
use: ["style-loader", "css-loader", "sass-loader",],
},
{
test: /\.(png$|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'assets/',
publicPath: 'assets/'
}
}
]
},
],
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'src/index.html'
}),
new webpack.HotModuleReplacementPlugin(),
new ErrorOverlayPlugin()
],
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 8080,
open: true,
historyApiFallback: true,
hot: true,
overlay: true,
}
}
tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": false,
"jsx": "react",
"esModuleInterop": true,
"baseUrl": "src",
"typeRoots" : ["node_modules/@types", "src/types"],
"allowSyntheticDefaultImports": true,
},
"include": ["src/**/*"],
"exclude": ["build"],
}
反應:
import React, { FC } from 'react'
import { NavLink } from 'react-router-dom'
import logo from '../../assets/images/logo.png'
const Header: FC = () => {
return (
<div className="header" id='header'>
<div className="logo">
<img src={logo} alt="logo"/>
<h1>Logo</h1>
</div>
</div>
);
}
export default Header;
我一直在頁面上看到照片,但錯誤仍然存在。
在src/
中創建一個declarations.d.ts
文件並添加declare module '*.png';
給它。
這應該可以解決問題,因為默認情況下,用戶定義的聲明應該 go 在src/
內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.