6

I am trying to take my first steps into working with typescript and I've run into an issue when trying to run my application.

I get the error ReferenceError: exports is not defined

the code I have is quite simple:

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

running tsc, it compiles and seems to work without any real issues, however when I try to run it with node build/index.js it crashes with this

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

ReferenceError: exports is not defined

It feels like I am missing something quite obvious, but I can't really seem to put my finger on it, so what am I missing?

12
  • Please use that code { "compilerOptions": { "module": "commonjs", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "es6", "noImplicitAny": true, "moduleResolution": "node", "sourceMap": true, "outDir": "dist", "baseUrl": ".", "paths": { "": [ "node_modules/" ] } }, "include": [ "src/**/*" ] } Commented Jan 11, 2020 at 16:54
  • no luck unfortunately :/ I get the same error even with that tsconfig Commented Jan 11, 2020 at 16:56
  • can you share your project ? Commented Jan 11, 2020 at 16:58
  • Replace the "outDir": "dist" with "outDir": "build" from the example @MaheshBhatnagar posted, or run it with node dist/index.js. You're probably still running the previously built code. Commented Jan 11, 2020 at 17:00
  • github.com/munHunger/soft-sync I did update the outDir, so it is pointing to what I assume is the correct file Commented Jan 11, 2020 at 17:02

1 Answer 1

11

You appear to have enabled Node's ES modules by setting "type": "module" in your package.json, but your tsconfig tells typescript to emit code compatible with CommonJS.

Either remove "type": "module", or configure tsconfig to emit code targeting ES modules.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.