typescript - 无法使 tsconfig 路径正常工作 (TS2307)
问题描述
这是我的tsconfig.json
:
{
"compilerOptions": {
"strict": true,
"importHelpers": false,
"inlineSources": true,
"noEmitOnError": true,
"pretty": true,
"module": "esnext",
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": false,
"removeComments": false,
"preserveConstEnums": false,
"sourceMap": true,
"lib": ["es2018","dom"],
"skipLibCheck": false,
"outDir": "dist",
"target": "es2018",
"declaration": false,
"resolveJsonModule": false,
"esModuleInterop": true,
"jsx": "preserve",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"baseUrl": ".",
"noEmit": true,
"paths": {
"@/*": ["./src/*"],
},
},
"files": [
"src/index.tsx"
],
"include": [
"src/**/*.d.ts"
]
}
跑步:
$ node_modules/.bin/tsc --noEmit
src/components/App.tsx:13:27 - error TS2307: Cannot find module '@/icons/info-circle.svg'.
13 import InfoCircleSvg from '@/icons/info-circle.svg';
~~~~~~~~~~~~~~~~~~~~~~~~~
src/components/pages/HomePage.tsx:2:20 - error TS2307: Cannot find module '@/images/gambit.jpg'.
2 import imgSrc from '@/images/gambit.jpg';
~~~~~~~~~~~~~~~~~~~~~
Found 2 errors.
但这些文件确实存在:
$ ll src/icons/info-circle.svg
-rw-r--r-- 1 mpen mpen 479 Mar 15 18:51 src/icons/info-circle.svg
paths
我已经尝试了所有我能想到的有和没有的排列*
,但我无法解决任何问题。baseUrl
设置.
为许多教程和帖子所建议的。我错过了什么?
是文件扩展名出错tsc
了吗?因为 webpack 可以很好地处理它们,而且我有一个选项应该选择的images.d.ts
文件:include
import { ElementType } from "react";
declare module "*.png" {
const content: string;
export default content;
}
declare module "*.jpg" {
const content: string;
export default content;
}
declare module "*.jpeg" {
const content: string;
export default content;
}
declare module "*.gif" {
const content: string;
export default content;
}
declare module "*.svg" {
const content: ElementType<React.SVGProps<SVGSVGElement> & { title?: string, desc?: string }>;
export default content;
}
解决方案
问题不在于路径,而在于声明文件。
要修复它,您可以将顶级导入移动到模块声明中:
declare module "*.svg" {
import { ElementType, SVGProps } from 'react';
const content: ElementType<SVGProps<SVGSVGElement> & { title?: string, desc?: string }>;
export default content;
}
或将其完全删除,然后:
declare module "*.svg" {
const content: React.ElementType<React.SVGProps<SVGSVGElement> & { title?: string, desc?: string }>;
export default content;
}
导入语句使文件模块,因此由模块扩充而不是模块声明declare module "*.svg"
考虑的语句。tsc
推荐阅读
- python - 我应该如何通过 TF2.1 将图像放入张量中?
- java - Java 线程减慢 Postgres 数据库更新
- ruby-on-rails - Rails 6 和 React 作为前端的 500 内部服务器错误
- javascript - Nodemailer 不尊重 rateDelta 和 rateLimit
- c# - 如何告诉 Unity 对象沿其父对象的每个轴的方向向前移动?
- wordpress - 获取 CPT 的父类别
- java - 带有身份验证的 okhttp 发布请求
- javascript - 能够在选择一个元素的值时更新另一个选择元素的值,反之亦然,使用 selectize
- blueprism - 如何在 Blue Prism 中阅读今天的一天?示例星期一
- oracle - Oracle DB 12c 到 19c 迁移 - 从应用程序的角度来看需要注意哪些事项