Skip to content

tsx

背景

不管是 Typescript 的编辑器 tscesbuildtransform api 在转译后并不会对路径进行重写操作。

  1. 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 正确的检测,确保编辑器不报类型错误。

  2. esbuildtransform api 不执行重写的原因

    可参考官方文档 的如下说明:

    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 的路径解析仅在构建阶段执行,所以 transform api 的转译并不会执行路径重写。

现有的解决方案

  1. tsc-alias

    tsc-alias 会在 tsc 转译 tsjs 文件后检查生成的 js 文件,然后根据 tsconfig.json 中的 complier.paths 配置项规则来替换掉别名路径。

    bash
    npx tsc && npx tsc-alias

    上面就是执行的指令,同时参考官方 issue可以看出 tsc-alias 是分步执行的,并不支持运行时使用。

  2. tsconfig-paths

    支持运行时加载和通过 API 加载。Typescript 默认模仿 Node.js 运行时模块解析策略。不一样的是 Typescript 也支持使用路径映射,允许指定任意模块路径(不以 "/""." 开头)并将其映射到文件系统中的物理路径。Typescript 编译器可以通过用户配置的tsconfig.jsonpaths 配置项来解析这些路径,因此会成功编译。但如果尝试使用 node(或 ts-node)执行 Typescript 编译后的 js 文件,则并不会尊重 tsconfig.json 中的 paths 配置项,而是会查找 node_modules 文件夹直至文件系统根目录。

    tsconfig-paths/register 模块会引导 node(或 ts-node)从 tsconfig.jsonjsconfig.json 读取路径,并将其转换为实例的物理文件路径。

    bash
    ts-node -r tsconfig-paths/register main.ts

    不过这需要额外安装 ts-nodetsconfig-paths 包,并且需要手动执行 ts-node -r tsconfig-paths/register main.ts 指令就显得有些麻烦了。

tsx 解决了上述的痛点,即在运行时就支持路径重写,同时还借助 esbuildtransform api 来快速转译 ts 文件,提高的执行效率。

Released under the MIT License. (bfe9f65)