NodeJS 如何将 JS 文件导入 TypeScript

NodeJS How to import JS file into TypeScript

我是 TypeScript 的新手。我目前正在学习使用 Typescript 语言的 NodeJS Loopback 4 框架。我的问题是如何将已在 JS 文件中导出的某些函数 class 导入到我的 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 文件中导入此函数时仍然出错

Error: Cannot find module './lib/test' at Function.Module._resolveFilename (module.js:543:15)

看起来 tsconfig.json 没有启用 'allowJs' 因为它导出了声明。

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

更新

可以找到到目前为止的完整聊天记录 here。 用于测试的存储库已找到 here

好的,@maaz-syed-adeeb 提到的解决方案很简单:

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

扩展之所以重要,是因为定义文件在 typescript 环境中优先于 javascript 文件。这就是模块导入失败的原因。

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

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

./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 和打字稿(假设您要使用现有代码库迁移到打字稿),则需要更新 tsconfig.json 以包含'在 IDE:

中获取警告
{
  "compilerOptions": {
    "allowJs": true,
    "declaration": false
  }
}

这样您的 javascript 文件将与打字稿文件一起转译到您的目标目录。