gpt4 book ai didi

javascript - 确保导入在 Typescript 中有效?

转载 作者:行者123 更新时间:2023-11-28 03:18:25 26 4
gpt4 key购买 nike

在基于 Typescript 的项目的构建或 linting 阶段,是否有任何方法可以确保所有导入:

  • 有效(路径不指向不存在的文件)
  • 已使用(没有未使用的导入)

问一下,因为我们最近遇到了一个问题,我们的项目似乎已经构建并通过了 linting,但由于遵循 CI/CD 的相对导入路径无效,无法在我们的开发服务器上运行。

例如,通过了构建步骤,但在运行时失败,因为实际路径应该是../utils/date:

import { parseDate } from '../../utils/date';

此外,以下内容显示为灰色,因为未在 Visual Studio Code 中使用,但未作为 linting 或构建的一部分捕获:

import { displayInfo } from '../../utils/display';

最佳答案

要修复项目中的相对路径错误,我建议您使用 typescript 别名方式。我的 typescript 配置:

jsconfig.path.json

{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"asssets/*": ["public/assets/*"],
"components/*": ["src/components/*"],
"hooks/*": ["src/hooks/*"],
"helpers/*": ["src/helpers/*"],
"screens/*": ["src/screens/*"],
"services/*": ["src/services/*"],
"state/*": ["src/state/*"],
"theme/*": ["src/theme/*"]
}
},
"include": ["src"],
"exclude": ["node_modules", "build", "coverage"]
}

最后,您应该将此文件扩展到 tsconfig.json 配置文件。

tsconfig.json

{
...
"extends": "./jsconfig.path.json",
...
}

它将传递您使用过的项目中的所有相对路径。

关于javascript - 确保导入在 Typescript 中有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59423738/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com