ts-node: Error: unknown file extension .ts

Expected Behavior

Load typescript files

Actual Behavior

When I try to execute a typescript file I get the following error message: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension “.ts” for /home/$USERNAME/$PATH_TO_DEV_FOLEDER/index.ts at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:65:15) at Loader.getFormat (internal/modules/esm/loader.js:113:42) at Loader.getModuleJob (internal/modules/esm/loader.js:243:31) at Loader.import (internal/modules/esm/loader.js:177:17)

Steps to reproduce the problem

launch ts-node index.ts

Minimal reproduction

Specifications

  • ts-node version: v8.10.2 (installed global)
  • node version: v14.3.0
  • TypeScript version:v3.9.3 (installed global)
  • tsconfig.json, if you’re using one:
{}
  • Operating system and version: Windows 10 Version 2004
  • If Windows, are you using WSL or WSL2?: Yes, Ubuntu 20.04 LTS in WSL2

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 97
  • Comments: 77

Commits related to this issue

Most upvoted comments

Remove “type”: “module” from package.json

Remove “type”: “module” from package.json

If remove module type, you cannot use imports in your .ts files

I must disagree. In Angular projects, there is no “type”: “module” in package.json and import synthax works fine. Try to set “module”: “es2020” in tsconfig.json

Closing as this is not a ts-node bug. If you want to use node’s native ESM support, which is currently experimental, then you can use ts-node’s experimental ESM loader hook. See #1007 for details.

This stack overflow answer helped me: https://stackoverflow.com/questions/63445821/ts-node-execute-typescript-with-module-import-and-module-defined

Updating my tsconfig.json to migrate from "module": "es6" to "module": "commonjs" allowed me to run my TypeScript file.

Estou tendo o mesmo problema também

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for www\server\src\server.ts at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:65:15) at Loader.getFormat (internal/modules/esm/loader.js:113:42) at Loader.getModuleJob (internal/modules/esm/loader.js:243:31) at Loader.import (internal/modules/esm/loader.js:177:17)

I’m having the same issue.

λ npx ts-node src/app.ts
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\Users\$USER\$PATH_TO_DEV_FOLDER\src\app.ts
    at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:65:15)
    at Loader.getFormat (internal/modules/esm/loader.js:113:42)
    at Loader.getModuleJob (internal/modules/esm/loader.js:243:31)
    at Loader.import (internal/modules/esm/loader.js:177:17)

I remove type: module from package json and it work

My earlier suggestion should point you in the right direction.

On Sun, Jun 21, 2020, 9:44 AM AguinaldoAlberto notifications@github.com wrote:

Estou tendo o mesmo problema também

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension “.ts” for www\server\src\server.ts at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:65:15) at Loader.getFormat (internal/modules/esm/loader.js:113:42) at Loader.getModuleJob (internal/modules/esm/loader.js:243:31) at Loader.import (internal/modules/esm/loader.js:177:17)

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/TypeStrong/ts-node/issues/1062#issuecomment-647130364, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAC35OCO5M3WUUNXSLA4YS3RXYFCVANCNFSM4NOUHHYQ .

ESM stuff? You might have better luck on our ESM thread. Or post a complete reproduction so someone else can debug.

I created a template repo which can be used by anyone who has trouble initializing ts-node.

From #1007, use node --loader ts-node/esm ./my-script.ts if your tsconfig.json contains "module": "commonjs"

I’d like to report some success just for any lost soul who’s found there way here. I’ve discovered the below works fine for me–and mind you, this is “all modern” Typescript output as well as the Node "type": "module" use case, so YMMV but it certainly works with all of @sindresorhus’s newest ESM-only packages (find-up, chalk etc.). Seems to also work for standard-issue CommonJS packages.

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "module": "esnext",
    "rootDir": "./src",
    "moduleResolution": "node",
    "types": ["node"],
    "resolveJsonModule": true,
    "outDir": "./dist/",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["./src/**/*.ts"]
}

package.json

{
    // ...
    "type": "module"
    // ...
}

and the ts-node command: node --experimental-specifier-resolution=node --loader ts-node/esm src/main.ts

This also works with tsc and node, you just need to be sure to specify the same resolution mode. So, something along the lines of tsc && node --experimental-specifier-resolution=node dist/main.js will work.

Node version I’m using right now is v14.17.3–probably need to update but newer versions of NPM have issues with the corporate Artifactory 🥲

Add this to the tsconfig.json:

  "compilerOptions": {
    "esModuleInterop": true
  }

and make sure to start the server with ts-node:

ts-node my_ts_node_server.ts

It is crazy how hard it was for me to find this. This will allow you to use imports as well as use typescript.

I added “type”: “module” in package.json and did npx tsx file.ts instead of using ts-node file.ts and it worked.

ts-node --skip-project scripts/yourFile.ts

I spent an hour banging my head against a wall this morning trying to figure this out - if you have a dependency in your project which uses “type”: “module” in it, it can also cause this problem. In my case, I had node-fetch@3.1.0. Downgrading to node-fetch@2.5.12 fixed it for me.

After hours lost this is the “solution”. Thanks.

Remove “type”: “module” from package.json

If remove module type, you cannot use imports in your .ts files

set the value of module to commonjs in tsconfig.json, it works for me.

{
"module": "commonjs",  
}

I spent an hour banging my head against a wall this morning trying to figure this out - if you have a dependency in your project which uses "type": "module" in it, it can also cause this problem. In my case, I had node-fetch@3.1.0. Downgrading to node-fetch@2.5.12 fixed it for me.

remove type: “module” and add in your tsconfig.json “compilerOptions”:{ “module”: “Commonjs”, “moduleResolution”: “node” }

Supported by ts-node 10.3.1

For me adding the --esm flag for ts-node --esm index.ts command did it.

This is what worked for me ts-node: 10.2.1 typescript: 4.4.2 node: 16.8.0

in package.json I removed “target”: “module”

in tsconfig.json I added this

“ts-node”: { “compilerOptions”: { “module”: “commonjs” }

an in a separate “compilerOptions” “module”: “ESNEXT”

I was getting a different error which is “Cannot use import statement outside a module” as a suggested solution in stack overflow I added “target”:“module” in package.json which lead me to this error: unknown file extension .ts

Hope it helps you out. I also found this article https://www.tsmean.com/articles/learn-typescript/typescript-module-compiler-option/

We’ve enabled the discussion forum for questions like this one.

https://github.com/TypeStrong/ts-node/discussions

We’re trying to keep the issue tracker limited to actionable tasks, so contributors can focus on making fixes and improvements to ts-node.

Since this is not a bug and nothing needs to change in ts-node, it’s not actionable, so it was closed. Discussions, on the other hand, are the perfect place to ask advice, share guides, and help with project configuration.

Another good thing about the discussion forum: you don’t need to fill out an issue template.

No matter what I do, I can’t get beyond “Unknown file extension “.ts””. My project is in TypeScript, and I’m trying to import an npm package (double-metaphone) that only working as an ESM import. Since I’m trying run my code using:

node --experimental-specifier-resolution=node --loader ts-node/esm app.ts

…it seems utterly bizarre that I would get an error complaining about the “.ts” extension. What other than “.ts” would the ts-node loader expect?

I’ve tried various combinations and permutations of suggestion here and elsewhere. My latest setup, running under Node.js v16.13.1, looks like this:

{
  "name": "my-project",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "start": "node --experimental-specifier-resolution=node --loader ts-node/esm app.ts",
  },
  "dependencies": {
    // blah, blah, blah
    "double-metaphone": "^2.0.0",
    // blah, blah, blah
  },
  "devDependencies": {
    // blah, blah, blah
    "ts-node": "^10.0.0",
    "typescript": "^4.5.4"
  }
}
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "sourceMap": true,
    "outDir": "./tsc-out",
    "noImplicitAny": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "noImplicitReturns": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2020",
      "dom"
    ]
  },
  "ts-node": {
    "esm": true
  }
}

Use ts-node --esm, ts-node-esm, or set "esm": true in tsconfig.json

https://typestrong.org/ts-node/docs/imports/

This is what worked for me. Not even ts-node-esm worked.

node --experimental-specifier-resolution=node --loader ts-node/esm file.ts

Let me just say that the entire ESM situation in Node.JS is a catastrophe. It created so much pain, incompatibility, lost hours. I don’t understand why some decisions were made that contributed to this pain. It’s probably not as bad as Python2 and Python3 but very close!

if your tsconfig.json contains “module”: “ESNext”. I have used the below script in my package.json. It worked.

 "start": "nodemon -e ts -w ./src -x npm run watch:serve",
 "watch:serve": "node --loader ts-node/esm src/server.ts",

I spent an hour banging my head against a wall this morning trying to figure this out - if you have a dependency in your project which uses "type": "module" in it, it can also cause this problem. In my case, I had node-fetch@3.1.0. Downgrading to node-fetch@2.5.12 fixed it for me.

What if you can not do that 😃? That’s not a solution.

Remove “type”: “module” from package.json

If remove module type, you cannot use imports in your .ts files

I’m having the same issue. how to fix, thx

@a-h Thank you bro! you the man!

Following this ts-node documentation CommonJS vs native ECMAScript modules worked for me.

This is the solution for me, hope it helps someone I’m using Express 4.17.3, Node 14.17.0

  • Install ts-node 10.7.0 as devDependencies
  • In package.json file, remove “type”: “module”
  • In tsconfig.json file, use “module”: “commonjs”

My package.json file:

{
  "name": "xxx",
  "version": "1.0.0",
  "main": "index.js",
  "author": "xxx",
  "license": "MIT",
  "scripts": {
    "ts-check": "tsc --noemit",
  },
  "dependencies": {
    "express": "^4.17.3",
    "tslib": "^2.3.1"
  },
  "devDependencies": {
    "@types/express": "^4.17.13",
    "@types/node": "^17.0.23",
    "ts-node": "^10.7.0",
    "typescript": "^4.6.3"
  }
}

My tsconfig.json file:

{
  "compileOnSave": false,
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "alwaysStrict": true,
    "baseUrl": ".",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "inlineSources": true,
    "isolatedModules": true,
    "lib": ["dom", "dom.iterable", "esnext"],
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noUnusedParameters": true,
    "noUnusedLocals": true,
    "paths": {
      "@routes/*": ["src/routes/*"],
      "@config/*": ["src/config/*"],
      "@controllers/*": ["src/controllers/*"],
      "@models/*": ["src/models/*"],
      "@utils/*": ["src/utils/*"],
      "@socket/*": ["socket/*"],
      "@src/*": ["src/*"],
    },
    "preserveConstEnums": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "target": "es5",
    "removeComments": true,
    "importHelpers": true,
    "typeRoots": ["./node_modules/@types"],
    "incremental": true
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules", "dist"]
}

@clinkadink thanks, that did it for me

What worked for me is ts-node --esm <filename>. No esModuleInterop or package.json changes

I must disagree. In Angular projects, there is no “type”: “module” in package.json and import synthax works fine. Try to set “module”: “es2020” in tsconfig.json

literally what does angular have to do with node??? doesn’t matter if you’re using babel. the question is about using typescript with node so thank you for reading and understanding the question carefully in order to provide constructive and helpful guidance. Great job author!

I need "type": "module" in package.json npx tsx ./file.ts worked for me

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

This worked for me. Thanks, @retrotechie 🚀

I just rm -rf dist and tsc & node dist/index.js again, then it works.

Solution 1:

Remove "type": "module" in package.json

Solution 2:

package.json

...
"type": "module"
...

tsconfig.json

"compilerOptions": {
...
"module": "ESNext",
...
},
"ts-node": {
  "esm": true
}

I’m not sure if we had better solutions but these worked for me.

For me adding --esm did not work. I received the error:

CustomError: Cannot find module '/home/mike/Code/company/app/src/backend/functions' imported from /home/mike/Code/company/app/do-thing.ts

The file /home/mike/Code/company/app/src/backend/functions.ts does exist (and I shouldn’t need the .ts to load it in TS).

However using npm tsx as others have mentioned did fix the problem and allowed my code to run perfectly.

From #1007, use node --loader ts-node/esm ./my-script.ts if your tsconfig.json contains "module": "commonjs"

Real quick follow up to this - running with this makes my code ~8x slower than ts-node by itself with changed options or just using tsc and node, and that’s testing the same exact function 10 times in a loop to mitigate the effects of the typescript JIT compilation times. Hopefully this is useful to someone?

This stack overflow answer helped me: https://stackoverflow.com/questions/63445821/ts-node-execute-typescript-with-module-import-and-module-defined

Updating my tsconfig.json to migrate from "module": "es6" to "module": "commonjs" allowed me to run my TypeScript file.

Thanks! it’s useful.

If you suddenly started getting this issue, this might be the cause: https://github.com/TypeStrong/ts-node/issues/2094

I spent an hour banging my head against a wall this morning trying to figure this out - if you have a dependency in your project which uses “type”: “module” in it, it can also cause this problem. In my case, I had node-fetch@3.1.0. Downgrading to node-fetch@2.5.12 fixed it for me.

After hours lost this is the “solution”. Thanks.

It is actually the solution 😄

I got this same error (Unknown file extension ".ts"), trying to run a typescript script with ts-node 10.9.1 and Node 20.10. I couldn’t find a solution unfortunately (I tried "esModuleInterop": true in tsconfig), but running the script through tsx worked, so I ended up migrating from ts-node to tsx.

I find it really odd that .ts files are not recognised by default. Surely ts-node should know how to handle .ts files?

for using esm add these

“module”: “CommonJS”,

That’s not true. ESM and CJS (CommonJS) are two different things, changing module to CommonJS will make tsc produce CommonJS code.

Remove “type”: “module” from package.json remain invalid

To all the poor souls still battling this like me: I might have a solution with ESM, "type: “module” and ts-node for VSCode. It involves adding a --loader runtime arg to launch.json. I hope it helps!

(Windows, Node 18.2.0)

package.json:

{
   ...
  "main": "source/main.js",
  "type": "module",
  "devDependencies": {
    "@types/node": "^18.6.1",
    "ts-node": "^10.9.1"
  }
}

tsconfig.json:

{
	"$schema": "https://json.schemastore.org/tsconfig",
	"display": "Node 16",
	"compilerOptions":
	{
		"esModuleInterop": true,
		"forceConsistentCasingInFileNames": true,
		"lib": ["es2020"],
		"module": "ESNext",
		"outDir": "output",
		"skipLibCheck": true,
		"strict": true,
		"target": "es2020"
	},
	"include": ["source"],
	"exclude": ["node_modules"],
	"ts-node":
	{
		"esm": true // from the top of https://typestrong.org/ts-node/docs/imports/
	}
}

launch.json:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
		{
			"name": "TS Debug",
			"type": "node",
			"request": "launch",
			"cwd": "${workspaceRoot}",
			"runtimeArgs": ["-r", "ts-node/register", "--loader", "ts-node/esm"],
			"args": ["${workspaceRoot}/source/runme.ts"]
		  }
    ]
}

With this, I can use ESM import/export, run the VSCode debugger, catch breakpoints in my TS files, etc…

NOTE: I have to use import paths with .js filenames, which seems odd, but works. The actual included file is .ts, and the debugger steps into the .ts file. Example: import * as JOE from ‘./joelib.js’; works with my file “./joelib.ts”.

Specifying the loader via NODE_OPTIONS did work form me, even though I had "esm": true in my tsconfig.json:

NODE_OPTIONS="--loader ts-node/esm" node ./index.ts

I must disagree. In Angular projects, there is no “type”: “module” in package.json and import synthax works fine. Try to set “module”: “es2020” in tsconfig.json

nope, same problem with import. “Warning: To load an ES module, set “type”: “module” in the package.json or use the .mjs extension.”

for me worked the opposite ( updated node to the latest 21.x version ) the ts-node config part in tsconfig.json

"ts-node": {
		"esm": false,
		"compilerOptions": {
			"module": "NodeNext"
		}
	},

same error in 2023

anyone code a tsx launch file for vscode that allows debugging?

if your tsconfig.json contains “module”: “ESNext”. I have used the below script in my package.json. It worked.

 "start": "nodemon -e ts -w ./src -x npm run watch:serve",
 "watch:serve": "node --loader ts-node/esm src/server.ts",

Using node 20 with sveltekit, this works

if your tsconfig.json contains “module”: “ESNext”. I have used the below script in my package.json. It worked.

 "start": "nodemon -e ts -w ./src -x npm run watch:serve",
 "watch:serve": "node --loader ts-node/esm src/server.ts",

Using node 20 with sveltekit, this works

if your tsconfig.json contains “module”: “ESNext”. I have used the below script in my package.json. It worked.

 "start": "nodemon -e ts -w ./src -x npm run watch:serve",
 "watch:serve": "node --loader ts-node/esm src/server.ts",

Using node 20 with sveltekit, this works

if your tsconfig.json contains “module”: “ESNext”. I have used the below script in my package.json. It worked.

 "start": "nodemon -e ts -w ./src -x npm run watch:serve",
 "watch:serve": "node --loader ts-node/esm src/server.ts",

Using node 20 with sveltekit, this works

Thank you😘

ts-node error ❌

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"

image

ESM solution ✅

image

"type": "module", & ts-node-esm

{
  "name": "patch-package-in-action",
  "version": "1.0.0",
  "description": "patch-package in action",
  "main": "./src/app.ts",
  "type": "module",
  "scripts": {
    "app-esm": "npx ts-node-esm ./src/app.ts",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/web-fullstack/patch-package-in-action.git"
  },
  "author": "xgqfrms",
  "license": "MIT",
  "dependencies": {
    "lodash-es": "^4.17.21",
    "typescript": "^5.0.2"
  },
  "devDependencies": {
    "@types/lodash-es": "^4.17.7",
    "app-node-env": "^1.4.7",
    "rimraf": "^4.4.0",
    "ts-node": "^10.9.1"
  }
}


{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

lodash-es

// ./src/app.ts

import {toString} from "lodash-es";

type Obj = {
  [key: string]: any;
}

const obj: Obj = {
  name: 'xgqfrms',
  country: 'China',
  language: 'zh-hans',
};

const str = toString(obj);
console.log(`toString =`, str1);

refs

https://typestrong.org/ts-node/docs/imports/

Receiving unknown file extension “.ts” error after upgrading wdio to 8 and Appium >16.

Detailed description here.

I added “type”: “module” in package.json and did npx tsx file.ts instead of using ts-node file.ts and it worked.

This work!

karlieli@Karlies-MacBook-Pro prisma_learn % npm run devStart

> prisma_learn@1.0.0 devStart
> node script.ts

node:internal/errors:484
    ErrorCaptureStackTrace(err);
    ^

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /Users/karlieli/Documents/mTeam/prisma_learn/script.ts
    at new NodeError (node:internal/errors:393:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:79:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:121:38)
    at defaultLoad (node:internal/modules/esm/load:81:20)
    at nextLoad (node:internal/modules/esm/loader:163:28)
    at ESMLoader.load (node:internal/modules/esm/loader:605:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:457:22)
    at new ModuleJob (node:internal/modules/esm/module_job:63:26)
    at #createModuleJob (node:internal/modules/esm/loader:480:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:434:34) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

Node.js v18.11.0
karlieli@Karlies-MacBook-Pro prisma_learn % npx tsx script.ts
{ id: 2, name: 'Kyle' }
karlieli@Karlies-MacBook-Pro prisma_learn % 

Very interesting but why npm doesn’t work?

I am trying to use Typescript from Webpack but latest Angular updated their webpack plugins to ESM. 😄 Eh, the ESM is such a disaster that one can only laugh. So many hours needlessly wasted. Unfortunately none of the solutions in this thread help.

For anyone who is running into this issue on CI or on Node.js 16.12.0, it seems like this latest version has made some changes to the hooks API 😱

https://github.com/nodejs/node/releases/tag/v16.12.0

Also mentioned here:

https://github.com/TypeStrong/ts-node/issues/1007#issuecomment-948484016

Add this to the tsconfig.json:

  "compilerOptions": {
    "esModuleInterop": true
  }

and make sure to start the server with ts-node:

ts-node my_ts_node_server.ts

It is crazy how hard it was for me to find this. This will allow you to use imports as well as use typescript.

Yup that works!!