typescript 中 referenceerror: exports is not defined 错误-ag捕鱼王app官网

typescript 中 referenceerror: exports is not defined 错误

作者:迹忆客 最近更新:2022/12/30 浏览次数:

要解决“uncaught referenceerror: exports is not defined”,添加一个定义导出变量的脚本标签,例如 如果在浏览器中,则在我们的 js 脚本标记之上,或者如果在 node.js 的 package.json 文件中设置为模块,则删除类型属性。


浏览器 - referenceerror: exports is not defined

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

<script>var exports = {};script>
<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 是一个不错的选择。

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


<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 的 exportsrequire 语法,我们必须坚持对所有导入和导出使用 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 模块语法来读取它们。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

在 typescript 中返回一个 promise

发布时间:2023/03/19 浏览次数:586 分类:typescript

本教程讨论如何在 typescript 中返回正确的 promise。这将提供 typescript 中 returns promise 的完整编码示例,并完整演示每个步骤。

在 typescript 中定义函数回调的类型

发布时间:2023/03/19 浏览次数:1445 分类:typescript

本教程说明了在 typescript 中为函数回调定义类型的ag捕鱼王app官网的解决方案。为了程序员的方便和方便,实施了不同的编码实践指南。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图