NodeJS 如何将 JS 文件导入 TypeScript

2024-01-09

我是 TypeScript 新手。我目前正在学习 NodeJS环回4使用 Typescript 语言的框架。我的问题是如何将 JS 文件中导出的一些函数、类导入到我的 TS 文件中。经过多种方式搜索后,但它仍然不适合我。 这是例子:

  // /src/index.ts
    import {plus} from './lib/test';

    console.log(plus(1,2));

// /src/lib/test.js
    export function plus(x, y) {
      return x + y;
    }

我也尝试使用这样的定义打字稿

// /src/lib/test.d.ts
export declare function plus(x: number, y: number): number;

但在index.ts文件中导入此函数时仍然出现错误

错误:找不到模块“./lib/test” 在 Function.Module._resolveFilename (module.js:543:15)


看起来 tsconfig.json 没有启用“allowJs”,因为它导出声明。

您是否有理由不希望这是一个打字稿文件?如果将 test.js 更改为 test.ts,通过将其设为 .ts 应该允许它在索引文件中被识别。

UPDATE

可以找到到达此点的完整聊天记录here https://chat.stackoverflow.com/rooms/187169/discussion-between-christopher-slater-and-quoc-van-tang。 用于测试的存储库已找到here https://github.com/chrisslater/loopback-test

好吧,@maaz-syed-adeeb 提到的简单解决方案将会起作用:

import { path } from './lib/test.js'

扩展名之所以重要,是因为在 TypeScript 环境中定义文件的优先级高于 JavaScript 文件。这就是模块导入爆炸的原因。

为了避免指定.js扩展您还可以像这样设置目录结构:

src
|- index.ts
|- lib
  |- test.js
  |- test.d.ts
  |- index.[js|ts]

in ./lib/index从测试中导出所有文件:

//./src/lib/index.[js|ts]
export * from './test'

然后从 lib 导入所有内容:

// ./src/index.ts
import { path } from './lib'
// or
import { path } from './lib/test.js'

如果您混合使用 javascript 和 typescript(假设您要使用现有代码库转向 typescript),则需要更新您的tsconfig.json包含在内,这样您就不会在 IDE 中收到警告:

{
  "compilerOptions": {
    "allowJs": true,
    "declaration": false
  }
}

这样您的 javascript 文件将与 typescript 文件一起被转换到您的目标目录。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NodeJS 如何将 JS 文件导入 TypeScript 的相关文章

随机推荐