How to execute a single TypeScript that uses `import type` file in ts-node

Viewed 124

I would like to execute a single TypeScript file using ts-node as a "module" to take advantage of the import type syntax.

When using the .ts extension, I get the warning Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. and then an error SyntaxError: Unexpected token 'export'.

When using the .mts extension, I get the error SyntaxError: Cannot use import statement outside a module.

What would I need to do to execute a single TypeScript file in ts-node and use import type without changing the type in package.json?

1 Answers

In my case, I'm using vite with react

In my tsconfig.json file, add in this section

{
...
"ts-node": {
    "compilerOptions": {
      "module": "commonjs"
    }
  },
}

then simply run npx ts-node path/to/your/script

Related