Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannnot use named import in an ESM project #940

Open
claabs opened this issue Feb 26, 2024 · 0 comments
Open

Cannnot use named import in an ESM project #940

claabs opened this issue Feb 26, 2024 · 0 comments

Comments

@claabs
Copy link

claabs commented Feb 26, 2024

In a JS project with "type": "module", in the package.json, the following code:

import { cancelable } from 'cancelable-promise';

will throw the error:

import { cancelable } from 'cancelable-promise';
         ^^^^^^^^^^
SyntaxError: Named export 'cancelable' not found. The requested module 'cancelable-promise' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'cancelable-promise';
const { cancelable } = pkg;

    at ModuleJob._instantiate (node:internal/modules/esm/module_job:132:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:214:5)
    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.1

As mentioned in the error, you can do this as a workaround:

import CancelablePromise from 'cancelable-promise';
const { cancelable } = CancelablePromise ;

However this issue still leads to unexpected failures as the error can only be caught at runtime. Typescript does not catch this error at compile time.


Ultimately, this comes down to how the export is declared in the package.json. You can see the root of the problem here: https://publint.dev/[email protected]

I'll open a PR to fix this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging a pull request may close this issue.

1 participant