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

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

当前回答

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

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

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

其他回答

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

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

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

我也犯了同样的错误。在我的例子中,这是因为我们在我们的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>

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

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

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

我在SSR客户端部分中遇到了这样的错误,因为它使用了一个用tsconfig构建的库。什么带来使用CommonJS模块解析tsc CLI选项编译器选项:目标=== "ES3"或"ES5" ?CommonJS: ES6。当它使用目标ESNext时。