Unknown file extension ".ts" with "type": "module"
node -r swc-register src/**/*.test.ts works as expected if "type": "module" is not present in package.json, otherwise the script fails with:
> node -r swc-register src/**/*.test.ts
internal/process/esm_loader.js:74
internalBinding('errors').triggerUncaughtException(
^
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /src/sum/sum.test.ts
at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:71:15)
at Loader.getFormat (internal/modules/esm/loader.js:104:42)
at Loader.getModuleJob (internal/modules/esm/loader.js:242:31)
at Loader.import (internal/modules/esm/loader.js:176:17)
at Object.loadESM (internal/process/esm_loader.js:68:5) {
code: 'ERR_UNKNOWN_FILE_EXTENSION'
}
Adding --experimental-specifier-resolution=node fixes it but the fails with:
> node --experimental-specifier-resolution=node -r swc-register src/**/*.test.ts
internal/process/esm_loader.js:74
internalBinding('errors').triggerUncaughtException(
^
TypeError [ERR_INVALID_MODULE_SPECIFIER]: Invalid module "file:///src/sum/sum.test.ts"
at Loader.getFormat (internal/modules/esm/loader.js:117:13)
at Loader.getModuleJob (internal/modules/esm/loader.js:242:20)
at Loader.import (internal/modules/esm/loader.js:176:17)
at Object.loadESM (internal/process/esm_loader.js:68:5) {
code: 'ERR_INVALID_MODULE_SPECIFIER'
}
Using node v14.17.0, .swcrc:
{
"minify": false,
"sourceMaps": true,
"env": {
"target": "node",
"mode": "entry",
"coreJs": 3
},
"module": {
"type": "es6"
},
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": false,
"decorators": false,
"dynamicImport": false
}
}
}
Thanks for reporting. An esm loader is needed to be implemented. I'll fix this later.
After taking another look, I'm not quite sure about how this should be implemented.
ts-node has given a good example https://github.com/TypeStrong/ts-node/blob/3a2848c9968f03f7b05e57e833ca256b52ab4e18/src/esm.ts but it involves many experimental features and immature specs. https://github.com/TypeStrong/ts-node/issues/1007
We should expect TypeScript supporting ESM first then consider what we should follow. This should be covered in TypeScript 4.6 (ideally). https://github.com/microsoft/TypeScript/issues/46452
If anyone has a better solution please let me know :)