mocha-examples icon indicating copy to clipboard operation
mocha-examples copied to clipboard

typescript with ts-node and ESM support

Open juergba opened this issue 4 years ago • 7 comments

Add a typescript sample using ts-node and node's native ESM support. Note: ts-node uses Node's loader-hooks which are still experimental.

You can find info: ts-node/1007 and a working sample: ts-node/discussion

juergba avatar Jun 16 '21 15:06 juergba

Thanks. Time permitting I'll send a pull request with a sample. Till then, I'm subscribed to this thread and can answer questions.

cspotcode avatar Jun 16 '21 16:06 cspotcode

I'm looking for a solution on this as well

Dunky13 avatar Sep 29 '21 08:09 Dunky13

FWIW, here's a configuration for Mocha, TypeScript, and ESM that finally worked for me: https://gist.github.com/jordansexton/2a0c3c360aa700cc9528e89620e82c3d

"node-option": ["experimental-specifier-resolution=node", "loader=ts-node/esm"] was the clincher.

jordaaash avatar Oct 25 '21 01:10 jordaaash

@jordansexton Thank you so much, that worked for me!

package.json

{
	"type": "module"
}

tsconfig.json

{
	"compilerOptions": {
		"module": "esnext",
		"moduleResolution": "node",
	}
}

.mocharc.json

{
	"node-option": [
		"experimental-specifier-resolution=node",
		"loader=ts-node/esm"
	]
}

henryruhs avatar Oct 26 '21 21:10 henryruhs

Thanks to all of you here, it helped me a lot :-)

I would simply add that one requirement is to use mocha@9 ([email protected] for me) as I was on mocha@8 and I was getting following error :

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

fcamblor avatar Jan 11 '22 08:01 fcamblor

Hi everyone else from search results.

This only works on node 16, ~haven't been able to get it to work on 18 or 20~.

Newer nodes don't like, and don't need(?) the "experimental-specifier-resolution=node",

FauxFaux avatar Mar 05 '24 12:03 FauxFaux