tsx
背景
不管是 Typescript 的编辑器 tsc 和 esbuild 的 transform api 在转译后并不会对路径进行重写操作。
tsc不执行重写的原因可参考官方文档的如下说明:
Note that this feature does not change how import paths are emitted by tsc, so paths should only be used to inform TypeScript that another tool has this mapping and will use it at runtime or when bundling.
可以看出
paths的配置项仅用来告知Typescript其他工具在运行时或构建阶段已经做了路径重写,对于Typescript自身来说,主要是引导Typescript正确的检测,确保编辑器不报类型错误。esbuild的transformapi 不执行重写的原因可参考官方文档 的如下说明:
These options affect esbuild's resolution of import/require paths to files on the file system. You can use it to define package aliases and to rewrite import paths in other ways. Note that using esbuild for import path transformation requires bundling to be enabled, as esbuild's path resolution only happens during bundling. Also note that esbuild also has a native alias feature which you may want to use instead.
因为
esbuild的路径解析仅在构建阶段执行,所以transformapi 的转译并不会执行路径重写。
现有的解决方案
tsc-alias会在tsc转译ts为js文件后检查生成的js文件,然后根据tsconfig.json中的complier.paths配置项规则来替换掉别名路径。bashnpx tsc && npx tsc-alias上面就是执行的指令,同时参考官方 issue可以看出
tsc-alias是分步执行的,并不支持运行时使用。支持运行时加载和通过
API加载。Typescript默认模仿Node.js运行时模块解析策略。不一样的是Typescript也支持使用路径映射,允许指定任意模块路径(不以"/"或"."开头)并将其映射到文件系统中的物理路径。Typescript编译器可以通过用户配置的tsconfig.json的paths配置项来解析这些路径,因此会成功编译。但如果尝试使用node(或ts-node)执行Typescript编译后的js文件,则并不会尊重tsconfig.json中的paths配置项,而是会查找node_modules文件夹直至文件系统根目录。tsconfig-paths/register模块会引导node(或ts-node)从tsconfig.json或jsconfig.json读取路径,并将其转换为实例的物理文件路径。bashts-node -r tsconfig-paths/register main.ts不过这需要额外安装
ts-node和tsconfig-paths包,并且需要手动执行ts-node -r tsconfig-paths/register main.ts指令就显得有些麻烦了。
tsx 解决了上述的痛点,即在运行时就支持路径重写,同时还借助 esbuild 的 transform api 来快速转译 ts 文件,提高的执行效率。
