node.jstypescriptes6-modulests-nodetypescript-execute

Use ts-node (or similar) to import both npm packages exported using ESM and CommonJS, using esm import


I would like a setup for my project with the following configurations.

  1. I would like to use typescript in my source code.
  2. I would like to use ESM only in my source code, ie. import foo from 'bar'.
  3. I do not want dist files outside npm_modules when executing my index.ts file.
  4. I would like to be able to load files exported with module.exports = ...
  5. I would like to be able to load files exported with export default { foo: ... }
  6. I don't want to use .mjs extensions.

Many of these features works out of the box with frameworks like next.js, vite.js, cra. However these all have alot of additional functionaliy and restrictions i do not want. For example a dev server which I do not need, and restrictions to where the src folder must be.

In short, I just want to execute self written typescript ESM files, using all sorts of 3rd party imports.

What is the best approach? Find and existing framework, like ts-node? Or setup something from scratch?

Any input on how to set this up, or which frameworks to check out is much appreciated.

What I am currently trying is ts-node, but i can't get ESM imports to work. I get a message saying i should set ´type´ to module in my package.json. But in my experiance this will prohibit loading of 3rd party code using CommonJS export.

Is it possible to set a specific loader for ts-node?


Solution

    1. tsx runner - https://github.com/esbuild-kit/tsx.
      tsx foo.ts to run, tsx --inspect watch foo.ts to start watcher with enabled inspector
    2. noEmit and esModuleInterop in tsconfig to avoid any outputs and allow importing cjs
    3. "type": "module" and "main": "src /index.ts" to run tsx .