程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何在不破坏打字稿的情况下将 CommonJS 库导入 ES Module 项目?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决如何在不破坏打字稿的情况下将 CommonJS 库导入 ES Module 项目??

开发过程中遇到如何在不破坏打字稿的情况下将 CommonJS 库导入 ES Module 项目?的问题如何解决?下面主要结合日常开发的经验,给出你关于如何在不破坏打字稿的情况下将 CommonJS 库导入 ES Module 项目?的解决方法建议,希望对你解决如何在不破坏打字稿的情况下将 CommonJS 库导入 ES Module 项目?有所启发或帮助;

我想用 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 模块使用,请参阅 @L_419_3@。
  • 使用方法 (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'.)。

大佬总结

以上是大佬教程为你收集整理的如何在不破坏打字稿的情况下将 CommonJS 库导入 ES Module 项目?全部内容,希望文章能够帮你解决如何在不破坏打字稿的情况下将 CommonJS 库导入 ES Module 项目?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。