Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Require typescript file after ts-node.register doesn't work in ESM #1986

Open
Fernando9995 opened this issue Apr 5, 2023 · 0 comments
Open

Comments

@Fernando9995
Copy link

Steps to reproduce the problem

index.mjs

import { dirname, resolve } from "path";
import { createRequire } from "module";
import tsnode from "ts-node";

const require = createRequire(import.meta.url);
const __dirname = dirname(decodeURI(new URL(import.meta.url).pathname)).replace(/^\/([A-Za-z]):\//, "$1:/");

tsnode.register({
  project: resolve(__dirname, "tsconfig.json"),
});

(() => {
  const res = require("./file.ts");
  res.init();
})();

Actual Behavior

Uncaught exception: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: ./file.ts require() of ES modules is not supported. require() of ./main.ts from ./index.mjs is an ES module file as it is a .ts file whose nearest parent package.json contains "type": "module" which defines all .ts files in that package scope as ES modules.
Instead change the requiring code to use import(), or remove "type": "module" from ./package.json.

Expected Behavior

There are no such error if start file from cmd

node --loader ts-node/esm --inspect ./file.ts

Specifications

  • ts-node version: v10.9.1
  • node version: v16.19.0
  • TypeScript version: v5.0.3
  • tsconfig.json, if you're using one:
{
  "compilerOptions": {
    "outDir": "_dist",
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "node16",
    "esModuleInterop": true
  },
  "ts-node": {
    "esm": true,
    "transpileOnly": true
  },
  "include": ["."]
}
  • package.json:
{
  "type": "module"
}
  • Operating system and version: Windows 10 22H2
  • If Windows, are you using WSL or WSL2?: WSL2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant