如何修复此打字稿文件“不是模块”错误?

Dan*_*ack 4 npm typescript

我刚刚将我的第一个库包发布到 NPM,并尝试在应用程序项目中使用它。

它是用 typescript 编写的,项目构建正常,并已发布到 NPM。但随后尝试使用它失败了,因为显然它不是一个有效的模块。

index.ts 文件中设置模块导出(afaik)的代码是:

const initByClass = (widgetBindings: WidgetClassBinding[], h: any, render: any) => {
  for (const widgetBinding of widgetBindings) {
    setupWidget(widgetBinding, h, render);
  }
};

module.exports = {
  initByClass
};
Run Code Online (Sandbox Code Playgroud)

库中的 tsconfig.json 文件是:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "target": "ES6",
    "module": "ES6",
    "moduleResolution": "node",
    "declaration": true,
    "outDir": "./lib",
    "strict": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "**/__tests__/*"]
}
Run Code Online (Sandbox Code Playgroud)

在我的应用程序代码中,我已将包添加到 package.json (并运行 npm update),并尝试使用以下命令将其导入应用程序入口文件中:

import { initByClass } from "widgety";
Run Code Online (Sandbox Code Playgroud)

但它给了我一个错误:

TS2306:文件“/var/app/app/node_modules/widgety/src/index.ts”不是模块。

我需要更改什么才能使代码可以导入到另一个打字稿项目中?

如果它们有用,所有项目文件: https: //github.com/Danack/widgety/ 以及 NPM 包条目: https: //www.npmjs.com/package/widgety

Ale*_*yne 9

当文件使用关键字导出值时,该文件被视为模块export

我相信module.exports =用这一行替换应该可以修复错误:

export default initByClass;
Run Code Online (Sandbox Code Playgroud)

请参阅此文档:https://www.typescriptlang.org/docs/handbook/modules.html

在 TypeScript 中,就像在 ECMAScript 2015 中一样,任何包含顶级import或 的文件export都被视为模块。相反,没有任何顶级导入或导出声明的文件被视为其内容在全局范围内可用的脚本(因此也适用于模块)。

使用importorexport使编译器将文件视为模块,而分配给module.exports或使用require()则不然。

出于这个原因以及其他原因,请始终在打字稿代码库中使用import和。export

  • 这个答案是正确的,但我想知道为什么。为什么我不能简单地使用 `module.exports` (3认同)