swc-project / swc-node

Faster ts-node without typecheck
MIT License
1.68k stars 67 forks source link

Using `@swc-node/register` with Mocha leads to errors #762

Closed martinslota closed 2 months ago

martinslota commented 3 months ago

When Mocha is used to run test files written in Typescript along with --import=@swc-node/register/esm-register, the following kind of error gets thrown:

Exception during run: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /path/to/test.spec.ts
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:160:9)
    at defaultGetFormat (node:internal/modules/esm/get_format:203:36)
    at defaultLoad (node:internal/modules/esm/load:143:22)
    at async nextLoad (node:internal/modules/esm/hooks:865:22)
    at async nextLoad (node:internal/modules/esm/hooks:865:22)
    at async Hooks.load (node:internal/modules/esm/hooks:448:20)
    at async MessagePort.handleMessage (node:internal/modules/esm/worker:196:18) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'

A specific reproduce along with a hacky fix can be found in this repository.

I'm not entirely sure what a proper fix would look like but I'd be happy to help with implementing it.

yeliex commented 3 months ago

LGTM. I would test later with more cases

martinslota commented 1 month ago

I tried adopting the fix released in version 1.9.1 but it seems that something else is now amiss:

$ npm test

> swc-node-register-mocha-bug@2.0.0 test
> node --import @swc-node/register/esm-register node_modules/mocha/bin/mocha test.spec.ts

file:///path/to/swc-node-register-mocha-bug/node_modules/mocha/bin/mocha.js:9
 */ const { loadOptions } = require('../lib/cli/options');
                            ^

ReferenceError: require is not defined in ES module scope, you can use import instead
    at file:///path/to/swc-node-register-mocha-bug/node_modules/mocha/bin/mocha.js:9:29
    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
    at async loadESM (node:internal/process/esm_loader:28:7)
    at async handleMainPromise (node:internal/modules/run_main:113:12)

Node.js v20.11.0

@yeliex Could we maybe reopen this issue? Or is it better if I report a separate new one?

martinslota commented 1 month ago

I opened a separate issue for the problem described above.

yeliex commented 1 month ago

@martinslota see https://github.com/swc-project/swc-node/pull/781