在使用 Typescript 的过程中,有时我们会使用别名导入模块,例如:
import { someFunction } from "@/utils";
上述代码中的 @
是我们在 tsconfig.json
文件中设置的别名,其实际路径可能为项目根目录下的 src/utils
。
然而,当我们在 utils
文件中写代码时,如果出现了错误,Typescript 的错误报告可能不太准确:
export function someFunction() {
const name: string = 123; // 将数字赋值给字符串类型,会报错
return name;
}
上述代码中将数字赋值给字符串类型,会导致编译错误,但是在使用别名导入时,Typescript 报告的错误信息会变成:
Type '123' is not assignable to type 'string'.
这可能会给我们带来困惑,因为我们不知道这个错误具体在哪个文件中发生了。
解决这个问题的方法是,在 tsconfig.json
文件中添加一个 paths
属性:
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
}
}
然后在项目根目录下创建 tsconfig-paths-bootstrap.js
文件,用于在运行时使用指定的别名路径:
const tsConfigPaths = require("tsconfig-paths");
const baseUrl = "./";
const { paths } = require("../tsconfig.json").compilerOptions;
tsConfigPaths.register({
baseUrl,
paths
});
最后,在启动项目时,在命令行中添加 --require ./tsconfig-paths-bootstrap.js
这一参数,即可使用别名路径并且得到准确的错误报告。例如:
ts-node --require ./tsconfig-paths-bootstrap.js index.ts
这样,在开发过程中,我们就可以放心地使用别名导入了。
下一篇:别名的条件语句