【问题标题】:exports is not defined when running compiled typescript运行编译的打字稿时未定义导出
【发布时间】:2020-04-28 23:09:19
【问题描述】:

我正在尝试使用 typescript 迈出第一步,但在尝试运行我的应用程序时遇到了问题。

我收到错误ReferenceError: exports is not defined

我的代码很简单:

// --src/changeset.ts
export enum ChangeAction {
  ADD,
  DELETE,
  MODIFY
}

export class Changeset {
  constructor(
    public version: Number,
    public content: String,
    public path: String,
    public action: ChangeAction
  ) {}
}

// --src/index.ts
import { Changeset, ChangeAction } from "./changeset";

const set = new Changeset(0, "Hello world", "/dev/null", ChangeAction.ADD);
set.version = 0;

console.log("Hello World! " + set.version);

// --tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "build"
  },
  "include": ["src/**/*"]
}

运行tsc,它可以编译并且似乎没有任何实际问题,但是当我尝试使用node build/index.js 运行它时,它会因此崩溃

build/index.js:2
Object.defineProperty(exports, "__esModule", { value: true });
                      ^

ReferenceError: exports is not defined

感觉好像我遗漏了一些非常明显的东西,但我似乎无法真正理解它,所以我遗漏了什么?

【问题讨论】:

  • 请使用该代码 { "compilerOptions": { "module": "commonjs", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "es6", "noImplicitAny":真,“moduleResolution”:“节点”,“sourceMap”:真,“outDir”:“dist”,“baseUrl”:“。”,“路径”:{“”:[“node_modules/" ] } }, "包括": [ "src/**/*" ] }
  • 不幸的是:/即使使用该 tsconfig 我也会遇到同样的错误
  • 你能分享你的项目吗?
  • "outDir": "dist" 替换为@MaheshBhatnagar 发布的示例中的"outDir": "build",或使用node dist/index.js 运行它。您可能仍在运行之前构建的代码。
  • github.com/munHunger/soft-sync 我确实更新了outDir,所以它指向我认为是正确的文件

标签: node.js typescript tsc


【解决方案1】:

您似乎通过在您的package.json 中设置"type": "module" 启用了Node's ES modules,但您的 tsconfig 告诉 typescript 发出与 CommonJS 兼容的代码。

要么删除 "type": "module",要么配置 tsconfig 以发出针对 ES 模块的代码。

【讨论】:

    猜你喜欢
    • 2019-05-01
    • 2018-04-17
    • 2018-01-21
    • 1970-01-01
    • 2018-02-18
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    相关资源
    最近更新 更多