React TypeScript项目导入自定义组件报错:模块未找到
React/Express+TypeScript 自定义组件「模块未找到」问题解决
问题回顾
开发React/Express+TS项目时,从node_modules导入模块正常,但自定义组件导入时报「模块未找到」错误,示例报错:
[0] ERROR in ./src/App.tsx 5:0-51 [0] Module not found: Error: Can't resolve './components/Counter/Counter' in '/home/name/Git/project/client/src' [0] [0] webpack compiled with 1 error
临时添加.tsx后缀能解决,但不符合TS项目常规做法,需要正确配置实现无后缀导入。
核心原因
问题出在TypeScript配置与Webpack解析规则不匹配:TS未被配置为自动识别.tsx后缀,同时Webpack也没设置对应解析规则,导致两者都无法找到无后缀的组件文件。
解决方案
1. 修正根目录tsconfig.json
更新配置,确保TS能覆盖client目录源码,并自动尝试.tsx等后缀:
{ "compilerOptions": { "target": "ESNext", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", // 让TS自动尝试这些后缀,无需手动添加 "moduleSuffixes": [".tsx", ".ts", ".js", ".jsx"] }, // 明确包含client目录下的所有源码文件 "include": ["./client/src/**/*"], "ts-node": { "esm": true, "experimentalSpecifierResolution": "node" } }
2. 配置Webpack解析规则(自定义Webpack场景)
如果项目是手动配置Webpack,需在webpack.config.js中添加.tsx到解析后缀列表:
module.exports = { // ...其他配置项 resolve: { extensions: ['.tsx', '.ts', '.js', '.jsx'], }, };
3. Create React App(CRA)场景适配
如果client端是用CRA创建的,根目录的tsconfig.json会被CRA内部配置覆盖,建议在client目录下单独创建tsconfig.json:
// client/tsconfig.json { "extends": "../tsconfig.json", "include": ["src/**/*"], "compilerOptions": { "moduleSuffixes": [".tsx", ".ts", ".js", ".jsx"] } }
CRA会优先读取当前目录的tsconfig.json,确保解析规则生效。
验证
修改配置后,重启开发服务器,尝试无后缀导入组件:
import Counter from "./components/Counter/Counter";
此时Webpack和TS都能正确识别组件文件,报错消失。
内容的提问来源于stack exchange,提问作者PirateCody
相关产品推荐
相关产品推荐

