简体   繁体   中英

using esm modules with ts-node

I successfully ran ts-node that transpiles to CommonJS modules. I used the official: docs

I also wanted to use esm modules following the officialesm docs , but was unfortunately unsuccessful. The error I keep getting is: CustomError: Cannot find module '/module/next/to/index/ts/ModuleName' imported from /Users/mainuser/angular_apps/typescript_test/index.ts

This is tsconfig.json

{
    "compilerOptions": {
      "target": "ES2015",                                 
      "module": "ES2020",                               
      "esModuleInterop": true,                             
      "forceConsistentCasingInFileNames": true,            
      "strict": true,                                      
         "skipLibCheck": true                                
    },
    "ts-node": {
      "esm": true
    }
  }
  

and this is the contest of package.json :

{
  "name": "typescript_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {},
  "devDependencies": {
    "ts-node": "^10.7.0",
    "typescript": "^4.6.3"
  },
  "type": "module"

}

I run ts-node with: ./node_modules/.bin/ts-node index.ts while being in the project root.

What am I missing?

This is my index.ts code:

import { SmokeTest } from "./SmokeTest";
SmokeTest.Log();

And this is the SmokeTest.ts file contents. Both are at the same fs level:

export module SmokeTest{
    export function Log(){
        console.log("Smoke test running");  
    }
}

I am running node v14.19.1 and ts-node v10.7.0

Adding ts-node to the tsconfig.json proved ineffective for me. I updated the tsconfig slightly ( see node14 base as a starting point):

{
  "compilerOptions": {
    "target": "ES2020",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "outDir": "build",
    "module": "es2020",
    "moduleResolution": "node"
  },
  "include": ["./*.ts"],
  "exclude": ["node_modules"]
}

I used the --loader ts-node/esm option:

$ node --loader ts-node/esm ./index.ts

I also updated my smoke-test.ts module to look like this:

function Log() {
  console.log('Smoke test running')
}

export const SmokeTest = { Log }

When importing with native esm modules, the extension must always be provided as .js for a .ts file:

import { SmokeTest } from './smoke-test.js'
SmokeTest.Log()

I believe with ts-node v10.9.1 you can use the --esm flag

yarn ts-node --esm path/to/file.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM