问题描述
我想用 Typescript 编写一个项目。该项目建立在 Typescript 编译器之上,所以我也在使用 typescript as a library,它 (AFAIK) 是一个 Commonjs 库。虽然该项目打算在 Node 上运行(而不是在浏览器中),但我想尽可能地构建这个项目以使用 ES 模块。换句话说,我在 "type": "module"
中设置了 package.json
。
示例项目
我在这里创建了一个可重现的示例:https://github.com/evertheylen/test-typescript-import。您可以使用 tsc && node build/test-typescript-compile-[...].js
运行文件。有两种方法:
1.标准 Typescript 导入
查看文件 test-typescript-compile-with-import.ts
:
import * as ts from "typescript";
// This will print: `The ts object has keys: ['default']`
console.log("The ts object has keys:",Object.keys(ts));
// This will of course fail
console.log(ts.createProgram(['foobar.ts'],{noEmitOnError: true}).emit());
在这里,Typescript 静态编译检查工作(即 ts.createProgram
被识别为正确的类型)。然而,在运行时 ts
对象只有一个 default
键(即为了实际运行 createProgram
我必须写 ts.default.createProgram
这是 Typescript 不允许的) .
2.使用 require
查看文件 test-typescript-compile-with-require.ts
(另见 the createRequire
docs):
import { createRequire } from 'module';
const require = createRequire(import.Meta.url);
const ts = require("typescript");
// This will print: `The ts object has keys: <lots of them>`
console.log("The ts object has keys:",Object.keys(ts));
// This will succeed!
console.log(ts.createProgram(['foobar.ts'],{noEmitOnError: true}).emit());
// The problem is that the 'ts' object is of type any,so (for example)
// the following typo won't be caught at compile time:
console.log(ts.createProogram(['foobar.ts'],{noEmitOnError: true}).emit());
这有效,但 Typescript 无法识别它,并且 ts
对象的类型为 any
,这不是我想要的(从示例中可以看出)。
可能的解决方案
- Typescript 暂时不会作为 ES 模块使用,请参阅 this issue。
- 使用方法 (1) 但以某种方式设置
ts = ts.default
(可能使用@ts-ignore
)。我无法让它工作,Node 会抱怨这个。像导入 ES 模块一样导入 Commonjs 库也感觉很hacky。 - 使用方法 (2) 但以某种方式让 Typescript 相信这个
ts
对象遵循与我导入的typescript
相同的类型。我阅读了declare
和.d.ts
文件的各种用法,但一无所获。
解决方法
我现在觉得有点傻,我搜索了“createRequire typescript”,在ts-node项目中遇到了这个commit:https://github.com/TypeStrong/ts-node/commit/a7aa0af9aefae1a7d801bbfe969148866c852a5c。它显示了在使用 typeof
时使用 require
。
我的解决方案归结为:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
import * as _ts from "typescript";
const ts: typeof _ts = require("typescript");
编辑:虽然这确实解决了 createProogram
等拼写错误的类型检查,但实际上并没有完全解决。特别是,您不能输入类似 options: ts.CompilerOptions
的内容,因为 ts
不被视为命名空间 (error TS2503: Cannot find namespace 'ts'.
)。