Typescript ReferenceError:未定义导出

新手上路,请多包涵

尝试按照 官方手册 实现模块,我收到此错误消息:

未捕获的 ReferenceError:未定义导出

在 app.js:2

但是在我的代码中,我从未使用过名称 exports

我怎样才能解决这个问题?


文件

应用程序.ts

 let a = 2;
let b:number = 3;

import Person = require ('./mods/module-1');

模块-1.t

  export class Person {
  constructor(){
    console.log('Person Class');
  }
}
export default Person;

tsconfig.json

 {
   "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": true,
        "outDir": "scripts/"
    },
    "exclude": [
        "node_modules"
    ]
}

原文由 George C. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

编辑:

如果您不再针对 es5 ,此答案可能不起作用,我将尝试使答案更完整。

原始答案

如果未安装 CommonJS( 定义 exports ),则必须从 tsconfig.json 中删除此行:

  "module": "commonjs",

根据评论,仅此一项可能不适用于 tsc 的更高版本。如果是这种情况,您可以安装一个模块加载器,如 CommonJS、SystemJS 或 RequireJS,然后指定它。

笔记:

查看 tsc 生成的 main.js 文件。你会在最上面找到这个:

 Object.defineProperty(exports, "__esModule", { value: true });

它是错误信息的根源,删除 "module": "commonjs", 后,它就会消失。

原文由 iFreilicht 发布,翻译遵循 CC BY-SA 4.0 许可协议

所以这是一个超级通用的 TypeScript 错误,这个 StackOverflow 问题是我研究问题的各种查询的第一个结果。它有 385,000 次观看。

对于那些使用 ng-packagr 的 Angular / TypeScript 和 Angular 库看到一个通用的“ ReferenceError:exports is not defined ”,您需要为每个功能/组件/服务定义 public-api.ts 以便包括它与 index.ts 例如在这篇 文章 的这个 repo 中找到

  • 节点 16 或 18(18 是下周的 LTS)
  • Angular 2+(目前 14 个)
  • 打字稿 4.6.4-4.8.2

几个浅的例子像这样引用 创建库

ng new workspace --no-create-application
cd workspace
ng generate app home --routing=true --style=scss
ng generate app admin --routing=true --style=scss
ng generate library lib
... # include your library 'lib' into your application 'home'
ng build lib --watch &
ng serve home --open

没有直接解释的是您的 index.tspublic-api.ts 文件需要在每个功能/组件/服务中。如果您有一个复杂的库,例如下面 repo 中的这些示例特性 A、B 和 C。 回购 有以下内容:

  • 源/库

原文由 kydreth 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进