尝试按照官方手册实现一个模块,我得到这个错误消息:

Uncaught ReferenceError:未定义exports 在app.js: 2

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

我该如何解决这个问题?


文件

app.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"
    ]
}

当前回答

注意:这可能不适用于OP的答案,但我得到了这个错误,这就是我解决它的方式。

所以我面临的问题是,当我从一个特定的CDN检索一个'js'库时,我得到了这个错误。

我做的唯一错误的事情是从CDN的cjs目录导入,就像这样: https://cdn.jsdelivr.net/npm/@popperjs/core@2.4.0/dist/cjs/popper.min.js

注意到dist/cjs部分了吗?这就是问题所在。

在我的例子中,我回到CDN (jsdelivr)并导航到umd文件夹。我可以找到另一组popper.min.js,这是要导入的正确文件: https://cdn.jsdelivr.net/npm/@popperjs core@2.4.0 / dist / / popper.min.js umd格式。

其他回答

我也犯了同样的错误。在我的例子中,这是因为我们在我们的TypeScript AngularJS项目中有一个老式的import语句,像这样:

import { IAttributes, IScope } from "angular";

它被编译成这样的JavaScript:

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

这在以前是需要的,因为我们在代码中使用了IAttributes,否则TypeScript不知道该用它做什么。 但是在删除import语句并将IAttributes转换为ng之后。IAttributes这两行JavaScript代码消失了——错误消息也消失了。

在其他JavaScript引用之前添加以下行。这是一个不错的小hack。

<script>var exports = {};</script>

对于仍然有这个问题的人,如果你的编译器目标设置为ES6,你需要告诉babel跳过模块转换。为此,将此添加到.babelrc文件中

{
  "presets": [ ["env", {"modules": false} ]]
}

通过将模块编译器选项设置为es6可以解决这个问题:

{
  "compilerOptions": {     
    "module": "es6",
    "target": "es5",    
  }
}

如果您只是为类型使用接口,那么省略export关键字,ts可以在不需要导入的情况下获取类型。关键是你不能在任何地方使用导入/导出。

export interface Person {
   name: string;
   age: number;
}

into

interface Person {
   name: string;
   age: number;
}