Search code examples
node.jstypescripttsc

Compile with tsc run with node, ReferenceError: exports is not defined in ES module scope


This question has been asked many times before, but I can not find a solution

I'm using typescript in my project.

I have my index.ts file which contains code like this:

import { getEnvOptions } from './env/envreader';
import express, {Express, Request, Response} from 'express';

When I compile this with command tsc and try to run it with node

I get an error saying:

Object.defineProperty(exports, "__esModule", { value: true });
ReferenceError: exports is not defined in ES module scope

As I understand the problem is that the node runtime environment doesn't recognize the keyword "exports" that is generated by the typescript compiler. I intend to run this project on a server and not in a browser which is why I set the "module" as "CommonJS".

Here's the tsconfig:

{
    "compilerOptions": {
  

      "target": "ES5",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */

      "module": "CommonJS",                                /* Specify what module code is generated. */

      "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */

       "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */

       "noEmit": false,                                   /* Disable emitting files from a compilation. */

      "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

      "strict": true,                                      /* Enable all strict type-checking options. */

      "skipLibCheck": true                          /* Skip type checking all .d.ts files. */
    },
    "include": ["./**/*.ts"],
    

  }

What exactly should I do to make this run in a node environment if I want to keep using the typescript import statements?


Solution

  • Remove "type": "module" from package.json since you can use imports without specifying that in package.json, the reason is because import is part of typescript.