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

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

当前回答

我的解决方案是上面所有东西的总和,我添加了一些小技巧,基本上我把这个添加到我的html代码中

<script>var exports = {"__esModule": true};</script>
<script src="js/file.js"></script>

这甚至允许你使用import而不是require,如果你使用electron或其他东西,它在typescript 3.5.1, target: es3 -> esnext中工作得很好。

其他回答

有同样的问题,并通过改变JS包的加载顺序来修复它。

检查调用所需包的顺序,并按适当的顺序加载它们。

在我的特定情况下(不使用模块绑定器),我需要加载Redux,然后Redux坦克,然后React Redux。在Redux坦克之前加载React Redux会给我出口是没有定义的。

要解决这个问题,将这两行放在index.html页面中。

<script>var exports = {"__esModule": true};</script>
<script type="text/javascript" src="/main.js">

确保检查main.js文件路径。

我认为问题可能是配置不匹配。

下面的工作解决方案1为您提供了ES模块的正确配置。 下面的工作解决方案2为您提供了正确的CommonJS配置。 混合解决方案1+2给你一个错误。

为了清晰起见,我在这里只发布了部分内容。 Github项目https://github.com/jmmvkr/ts-express/ 准备一套完整的文件来演示工作解决方案1和解决方案2。

工作方案1,ES模块

/* Configuration for ES Module */

// tsconfig.json
{
    "compilerOptions": {
        "module": "es6", // or "esnext"
    }
}
// package.json
{
    "type": "module", // type is module
}

工作解决方案2,CommonJS

/* Configuration for CommonJS */

// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
    }
}
// package.json
{
    "type": "", // type is NOT module
}

混合,不工作

/* Mixed, got ReferenceError: exports is not defined in ES module scope */

// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
    }
}
// package.json
{
    "type": "module", // type is module
}

简单地添加libraryTarget: 'umd',就像这样

const webpackConfig = {
  output: {
    libraryTarget: 'umd' // Fix: "Uncaught ReferenceError: exports is not defined".
  }
};

module.exports = webpackConfig; // Export all custom Webpack configs.

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

import { IAttributes, IScope } from "angular";

它被编译成这样的JavaScript:

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

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