typescriptes6-modulests-node

ts-node: importing a JS file that uses import and export


I'm trying to get this script running using the ts-node command:

// my-script.ts
import SearchIntegrator from "search-integrator/src/main/search-integrator"
console.log(SearchIntegrator)

But it seems that the SearchIntegrator NPM package is using import statements internally:

// search-integrator.js
import Parser from "./backend/parser/parser.js";
// …

…which is causing this error:

$ ts-node my-script.ts
Error [ERR_REQUIRE_ESM]: require() of ES Module /node_modules/search-integrator/src/main/search-integrator.js from my-script.ts not supported.

I've spent the last couple of hours trying out all sorts of config option combinations I've found online. For example:

{
  "ts-node": {
    "esm": true
  }
}

…or

{
  "ts-node": {
    "compilerOptions": {
      "module": "commonjs",
      "esModuleInterop": true
    }
  }
}

…or even "moduleResolution": "node".

However, the only thing it affected were the error messages, like Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6.

The more options I've tried the less I understood. I'm really only trying to import that NPM module on which I have no impact code-wise.

I'm also open for other tools if ts-node isn't the way to go.

I'm using the latest LTS Node (v18) and the latest version of ts-node (v10).


Solution

  • For simplicity reasons I've deleted both tsconfig.json and package.json and got it working by renaming my-script.ts to my-script.mts and running it using this command:

    ts-node --esm --compilerOptions '{ "module": "esnext" }' my-script.mts