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

TypeError: Unknown file extension ".ts" - esmodules support

Open AuroraLantean opened this issue 2 years ago • 40 comments

Original post in Anchor repo: [(https://github.com/project-serum/anchor/issues/1286)]

Anchor.toml [script] command: test = "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts"

The problem is the m1.ts file cannot import functions from another ts file!!!??? in my utils.ts

export const log1 = console.log;

in my m1.ts file:

import { log1 } from './utils';
describe('scenario1', async () => {
  it('initialize', async () => {
    log1('\n---------== init');
  });
});

the imported log1 function or any other function will cause the Unknown file extension ".ts" error!!??

my local package dependencies: "mocha": "^9.1.3", "ts-mocha": "^9.0.0-alpha1", "ts-node": "^10.4.0", "typescript": "^4.5.4"

Please advise. Thank you unknown file extension ts2

AuroraLantean avatar Jan 12 '22 09:01 AuroraLantean

please test with new v9.0.0 9.0.0-alpha1 is experimental

piotrwitek avatar Jan 12 '22 15:01 piotrwitek

Thank you for your post... but "ts-mocha": "9.0.0" results in the same error as above.

AuroraLantean avatar Jan 13 '22 03:01 AuroraLantean

@AuroraLantean need a little bit of help, if you could help me to create a simple repo with your setup (package.json and m1.ts + utils.ts files and npm test command) I would try to investigate that repo and fix that issue and also look for a way to add it to the regression testing for your use-case. 

I guess it's related to the ts-node version, not sure why you have installed it in your project but it's different from ts-mocha version possibly clashing.

piotrwitek avatar Jan 13 '22 16:01 piotrwitek

Hi @piotrwitek , thank you for your quick reply. Please take the following code: https://github.com/AuroraLantean/SolanaAnchorDemo2 Thank you!

AuroraLantean avatar Jan 14 '22 11:01 AuroraLantean

For another example, I was able to reproduce it with the following repo after installing/using dateformat: https://github.com/Burwin/ts-mocha-file-extension

Burwin avatar Jan 20 '22 18:01 Burwin

Pretty sure this is due to type: module in package.json (possibly in a dep). See the ts-node issue for this.

Not sure how to mangle ts-mocha into doing the right thing here? Something like node --loader=ts-node/esm ts-mocha ... should be enough, but doesn't work for me, perhaps ts-mocha needs to support --loader itself?

simonbuchan avatar Feb 02 '22 05:02 simonbuchan

Try ts-mocha -n loader=ts-node/esm -p tsconfig.json tests/**/*.test.ts via npm scripts, it works for me! (Optional) Check npx ts-mocha --help for more details of this option.

cn-ia avatar Feb 20 '22 14:02 cn-ia

Hello, having the same issue here. Trying @cn-ia solution did not work for me

DoodahProductions avatar Mar 01 '22 22:03 DoodahProductions

If that can help, I found out that this issue seems to be triggered when I do use the package get-port version >= ^6.0.0 If I do remove this package, tests are running correctly. If I add this package, then my test command produce the error TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"

Test command :

"test": "ts-mocha -p tsconfig.json 'test/**/*.ts'",

TsConfig:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "composite": true,
    "outDir": "dist",
    "rootDir": ".",
    "sourceMap": true,
    "strict": false,
    "declaration": true,
    "esModuleInterop": true,
    "resolveJsonModule": true
  },
  "include": [
    "./**/*.ts",
    "src/definitions/**/*.json",
    "src/modules/tasks"
  ],
  "exclude": [
    "node_modules",
    "dist",
    "test"
  ]
}

DoodahProductions avatar Mar 01 '22 23:03 DoodahProductions

Pretty sure this is due to type: module in package.json (possibly in a dep). See the ts-node issue for this.

Not sure how to mangle ts-mocha into doing the right thing here? Something like node --loader=ts-node/esm ts-mocha ... should be enough, but doesn't work for me, perhaps ts-mocha needs to support --loader itself?

For me, this was the problem. Removing "type": "module" from package.json fixed the problem for me.

sagrawal31 avatar May 05 '22 08:05 sagrawal31

Hey! I have the same issue. I do not have "type": "module" in my package.json so it might be something else. Honestly my package.json is extremely simple so it's doubtful that it originates from there. I'm using ts-mocha version 10.0.0 and ts-node version 10.7.0.

SmashingQuasar avatar May 18 '22 17:05 SmashingQuasar

@SmashingQuasar I believe the issue is because ts-mocha depends on [email protected] which didn't support ESM it would need to depend on 10+ or to have it as a peer dependency although that would force all developers to install ts-node themselves even if they don't use ts-node for other reasons.

If you run npm ls ts-node in your project you should see something like:

@my-project@ /Users/myuser/projects/my-project
├─┬ [email protected]
│ └── [email protected]
└── [email protected]

Showing that although your project uses a newer ts-node version ts-mocha still uses an older version.

felipeplets avatar Jun 05 '22 19:06 felipeplets

Hello Everyone, thanks for multiple useful contributions here in this issue, I'll try to look into this issue today and propose some solutions, also I will try to include a special test case scenario on a branch in the repo to help with debugging. Cheers!

piotrwitek avatar Jun 09 '22 11:06 piotrwitek

I have created a branch with a reproduction test case for experimentation here: https://github.com/piotrwitek/ts-mocha/tree/support-for-node-es-modules

After some research, the issue was indeed introduced by ts-node dependency not handling esmodules and I found some solutions we could try to implement:

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

More details on ts-node esm support:

  • https://github.com/TypeStrong/ts-node/issues/1007
  • https://github.com/TypeStrong/ts-node/discussions/1450
  • https://github.com/TypeStrong/ts-node/issues/935

I won't have time to work on it anytime soon, but will try to help and accept PRs for this. Cheers!

piotrwitek avatar Jun 09 '22 14:06 piotrwitek

Let me know if you need guidance on the best way to use our ESM loader.

cspotcode avatar Jun 21 '22 22:06 cspotcode

Same issue.

fiftin avatar Jul 05 '22 17:07 fiftin

Same issue

yasinkocak avatar Jul 14 '22 13:07 yasinkocak

same issue

hebelal avatar Jul 29 '22 09:07 hebelal

Just ran into the same issue myself.

gliese1337 avatar Aug 16 '22 23:08 gliese1337

Hello everyone,I have the same problem and I think the problem was caused by tsconfig.json

// ❌ when module = esnext
{
	"compilerOptions": {
    	"module": "esnext"
    }
}
// ✅ change module to commonjs,then everything is ok
{
	"compilerOptions": {
    	"module": "CommonJS"
    }
}

Hope this trick can help.

manooog avatar Aug 17 '22 01:08 manooog

I got the same issue with package.json:

"scripts": 
    "test": "mocha --require ts-node/register test/**/*_spec.ts",
},
"devDependencies": {    
      "@types/chai": "^4.3.3",
      "@types/mocha": "^9.1.1",
      "chai": "^4.3.6",
      "mocha": "^10.0.0",
      "ts-mock-imports": "^1.3.8",
      "ts-node": "^10.9.1",
      "typescript": "^4.8.3"
}

attempt to run test npm run test throws this:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /somepath/test/binding/cookieNumArray_spec.ts
    at new NodeError (node:internal/errors:372:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:80:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:122:38)
    at defaultLoad (node:internal/modules/esm/load:21:20)
    at ESMLoader.load (node:internal/modules/esm/loader:431:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:350:22)
    at new ModuleJob (node:internal/modules/esm/module_job:66:26)
    at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:369:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:328:34)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:409:24)
    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
    at async formattedImport (/somepath/node_modules/mocha/lib/nodejs/esm-utils.js:7:14)
    at async Object.exports.requireOrImport (/somepath/node_modules/mocha/lib/nodejs/esm-utils.js:38:28)
    at async Object.exports.loadFilesAsync (/somepath/node_modules/mocha/lib/nodejs/esm-utils.js:91:20)
    at async singleRun (/somepath/node_modules/mocha/lib/cli/run-helpers.js:125:3)
    at async Object.exports.handler (/somepath/node_modules/mocha/lib/cli/run.js:370:5)

janholusa avatar Sep 22 '22 07:09 janholusa

seems like a problem with Node itself, if someone can make a working example using mocha and ts-node I would be able to integrate it into the library

piotrwitek avatar Sep 22 '22 11:09 piotrwitek

Needs the --loader flag, due to node limitations. Node does not allow programmatic API nor --require to hook ESM.

cspotcode avatar Sep 22 '22 14:09 cspotcode

@cspotcode thanks for jumping in and correcting my assumptions! Could you point me to some examples or solutions that are using mocha and ts-node with ESM successfully that I could try?

piotrwitek avatar Sep 22 '22 16:09 piotrwitek

Google found this: https://github.com/TypeStrong/ts-node/discussions/1268

cspotcode avatar Sep 22 '22 16:09 cspotcode

create .mocharc.json and

{ 
    "node-option": [
	 "loader=ts-node/esm"
     ]
}

h-unterp avatar Oct 04 '22 21:10 h-unterp

In my case, on of my dependencies (nanoid) added "type": "module" to their package.json. I had to downgrade nanoid to fix mocha.

Windovvsill avatar Oct 17 '22 17:10 Windovvsill

Nanoid got me too

nmklotas avatar Feb 04 '23 18:02 nmklotas

same problem here, and I need to use type: module

Polve avatar Mar 01 '23 10:03 Polve

came across this today

"ts-mocha": "^10.0.0"
➜  fireproof git:(main) ✗ pnpm test

> @fireproof/[email protected] test /Users/nikos/WebstormProjects/fireproof-nikos-clone/packages/fireproof
> npm run test:mocha


> @fireproof/[email protected] test:mocha
> ts-mocha test/*.test.ts


TypeError: Unknown file extension ".ts" for /Users/nikos/WebstormProjects/fireproof-nikos-clone/packages/fireproof/test/clock.test.ts
    at new NodeError (node:internal/errors:399: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:64:26)
    at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:480:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:434:34)```

![Uploading image.png…]()

quantuminformation avatar Apr 22 '23 11:04 quantuminformation