Skip to content

TSX

Background

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

    Module resolution 中提到:

    TypeScript doesn’t modify import specifiers during emit: the relationship between an import specifier and a file on disk (if one even exists) is host-defined, and TypeScript is not a host.

    告知了 TypeScript 不重写导入路径的根本原因:

    导入说明符(import specifier)与实际文件之间的关系是由 宿主环境 定义的,而 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 的路径解析特性仅在 构建阶段 会执行,转译阶段并不会执行路径重写。

Existing Solutions

  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 文件,提高的执行效率。

Contributors

Changelog

Discuss

Released under the CC BY-SA 4.0 License. (0850f0c)