TypeScript 中 ReferenceError: exports is not defined 错误

要解决“Uncaught ReferenceError: exports is not defined”,添加一个定义导出变量的脚本标签,例如 <script>var exports = {};</script> 如果在浏览器中,则在我们的 JS 脚本标记之上,或者如果在 Node.js 的 package.json 文件中设置为模块,则删除类型属性。


浏览器 – ReferenceError: exports is not defined

如果在浏览器中运行的代码出现错误,请尝试在加载 JS 文件的脚本标签上方定义一个全局导出变量。

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

<!-- 👇️ your JS script should be below -->
<script src="index.js"></script>

这定义了 exports 变量并将其设置为一个空对象,因此如果访问它的属性,我们不会收到错误。

浏览器不支持 require 和 module.exports 的 CommonJS 语法(除非你使用 webpack 之类的工具),这会导致错误。

如果我们在浏览器中运行代码,请尝试从 tsconfig.json 文件中删除模块属性并将目标设置为 es6。

{
  "compilerOptions": {
    "target": "es6",  // 👈️ set this to es6
    // "module": "commonjs", // 👈️ REMOVE this (if browser env)
  }
}

当我们删除模块选项并将目标设置为 es6 时,我们的 ES6 模块导入和导出将不会被编译为浏览器不支持的旧 CommonJS 语法。

现代浏览器支持所有 ES6 特性,因此 ES6 是一个不错的选择。

如果这不起作用,请尝试在脚本标签中将类型属性设置为模块。

<!-- 👇️ correct path according to your setup -->
<script type="module" src="index.js"></script>

并使用 ES6 模块语法导入和导出。

import {v4} from 'uuid'

export function sum(a, b) {
  return a + b;
}

当我们在 tsconfig.json 中将模块设置为 commonjs 时,指示 TypeScript 发出 CommonJS 文件,而浏览器不支持 CommonJS 语法,因此这很可能是导致错误的原因。


Node.js – ReferenceError: exports is not defined

如果我们在 Node.js 应用程序中遇到错误,请尝试从 package.json 文件中删除类型属性(如果它设置为模块)。

{
  "type": "module", // 👈️ remove this
}

当 type 设置为 module 时,我们无法使用 CommonJS 的 exports 和 require 语法,我们必须坚持对所有导入和导出使用 ES Modules 语法,这可能会导致错误。

当我们在 package.json 文件中将类型设置为 module,但在 tsconfig.json 文件中将模块设置为 commonjs 时,就会发生这种情况。

这两个选项不兼容,因为 type = module 指示 Node.js 使用 ES 模块语法,而 module = commonjs 指示 TypeScript 发出 CommonJS 文件。

打开我们的 tsconfig.json 文件并确保它类似于以下内容。

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "esModuleInterop": true,
    "moduleResolution": "node",
    // ... your other options
  }
}

你的目标选项应该至少是 es6 并且模块应该设置为 CommonJS。

确保使用 ES6 模块语法进行导入和导出。

import {myFunction} from './myFile'

export function sum(a:number, b:number) {
  return a + b;
}

Node JS 支持 CommonJS 语法,因此当我们使用 ES module 语法并通过将模块设置为 commonjs 来指示 TypeScript 发出 CommonJS 代码时,上面示例中的导出将被编译为 CommonJS 并且应该可以工作。

它不起作用的唯一原因是——你发出了 CommonJS 文件,但已指示 Node.js 使用 ES6 模块语法来读取它们。