node-csv: Cannot import when `moduleResolution: node16` is set for typescript
Describe the bug
Getting
main.ts:1:23 - error TS1471: Module 'csv-parse' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead.
when trying to import in a project with moduleResolution: node16.
To Reproduce
package.json
{
"dependencies": {
"csv-parse": "5.3.0",
"typescript": "4.7.4"
}
}
tsconfig.json
{
"compilerOptions": {
"moduleResolution": "Node16"
}
}
main.ts
import { parse } from 'csv-parse';
and then run:
tsc
Output I get:
$ tsc
main.ts:1:23 - error TS1471: Module 'csv-parse' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead.
1 import { parse } from 'csv-parse';
~~~~~~~~~~~
Found 1 error in main.ts:1
Additional context
My intent in this example is to import csv-parse using require, but typescript seems to think this library only exposes esm modules.
Typescripts esm support is not without controversies. One of them is that they are more strict about the location of .d.ts files: https://github.com/microsoft/TypeScript/issues/49160 . The most straightforward solution seems to be just duplicating the type definitions beside all entry points, but there might be better ways I am not aware of.
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 22 (16 by maintainers)
Commits related to this issue
- fix: support ts node16 resolution in cjs (#354) — committed to adaltas/node-csv by wdavidw 4 years ago
@wdavidw I’ve added a demo illustrating the issue: https://github.com/jonmast/node-csv/tree/master/demo/ts-moduleresolution-node16-cjs
Running:
npx run typecheckin that directory should return the error.I believe this happens with the combination of
module: commonjs,moduleResolution: node16(in tsconfig), andmodule: false(in package.json). The fix is to use.d.ctsfiles as @acidoxee said.