Skip to content

Cannot import when moduleResolution: node16 is set for typescript #354

Closed
@sorgloomer

Description

@sorgloomer

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: microsoft/TypeScript#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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions