Typescript example: Can't use ES modules imports with Node.js AND uvu
See original GitHub issueThanks for the tool @lukeed!
I’m having an issue with the Typescript example:
I’m trying to use ES modules directly, with the latest version of Node.js, but I can’t make test modules to work at the same time, when using imports between source modules.
I added the following (which I think it’s a pretty common use case), to the typescript example you provided:
- Added
"type": "module"
topackage.json
file, so I can use ES modules with Node.js - Added
src/main.ts
file with the following content:
import { sum } from './math'
export function run() {
console.log(sum(2, 3))
}
run()
- Added
tests/main.ts
file with the following content:
import { test } from 'uvu';
import * as assert from 'uvu/assert';
import * as main from '../src/main';
test('run', () => {
assert.type(main.run, 'function');
});
- Build and test:
yarn build && yarn test
Tests work! But when I try to run emmited files with Node.js, got the following error:
node build/main.js
internal/modules/run_main.js:54
internalBinding('errors').triggerUncaughtException(
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/cristian/projects/uvu-typescript-example/build/math' imported from /home/cristian/projects/uvu-typescript-example/build/main.js
This is because ES modules imports need explicit file extension. So I fix the issue adding imports file extensions to src/main.ts
(which is supported by Typescript)
import { sum } from './math.js'
...
Now building and running main file works:
yarn build && node build/main.js
yarn run v1.22.4
$ tsc
Done in 2.44s.
5
but tests don’t 😦 (got the following error):
yarn test
yarn run v1.22.4
$ uvu -r ts-node/register tests
(node:28693) UnhandledPromiseRejectionWarning: Error: Cannot find module './math.js'
Tried different tsconfig.json
configurations, but can’t make the emmited files and test files to work at the same time.
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (4 by maintainers)
Top GitHub Comments
Oh, sorry – forgot the second half of your predicament. TypeScript can’t output
mjs
files (whichtype: "module"
addresses) nor modify the output links (which is still unaddressed & causes the error you see).I’d recommend passing everything through Rollup – here’s an example TS+Rollup setup.
But if you want to use this example as your boilerplate, you can do so by following this guide: https://github.com/microsoft/TypeScript/issues/18442#issuecomment-581738714
You’re only missing step 3:
--experimental-specifier-resolution=node
With that, you invoke the OG module-resolution algorithm which allows you to have extension-less importsYou’re welcome, happy to help! 😃