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

Files ending in .mjs, but show Error: Unexpected import statement in CJS module. #35425

Closed
bahuwang opened this issue Sep 30, 2020 · 1 comment

Comments

@bahuwang
Copy link

  • Version: 14.13.0
  • Platform: windows 10
  • Subsystem:

What steps will reproduce the bug?

@angular/core module file. https://github.com/bahuwang/issue/blob/master/core.js
demo.mjs file. https://github.com/bahuwang/issue/blob/master/demo.mjs
Just one line of code:

import { EventEmitter } from './core.js';

It is an ES modules, not CommonJS.

internal/deps/cjs-module-lexer/lexer.js:882
      throw new Error('Unexpected import statement in CJS module.');
            ^

Error: Unexpected import statement in CJS module.
  at @:7:8
?[90m    at throwIfImportStatement (internal/deps/cjs-module-lexer/lexer.js:882:13)?[39m
?[90m    at parseSource (internal/deps/cjs-module-lexer/lexer.js:83:13)?[39m
?[90m    at parseCJS (internal/deps/cjs-module-lexer/lexer.js:38:5)?[39m
?[90m    at cjsPreparseModuleExports (internal/modules/esm/translators.js:193:34)?[39m
?[90m    at Loader.commonjsStrategy (internal/modules/esm/translators.js:143:35)?[39m
?[90m    at new ModuleJob (internal/modules/esm/module_job.js:38:41)?[39m
?[90m    at Loader.getModuleJob (internal/modules/esm/loader.js:245:11)?[39m
?[90m    at async ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:53:21)?[39m
    at async Promise.all (index 0)
?[90m    at async link (internal/modules/esm/module_job.js:58:9)?[39m {
  loc: ?[33m109?[39m
}

@guybedford
Copy link
Contributor

@bahuwang the problem here is that Node.js thinks that core.js is a CommonJS module not an ES module. To tell Node.js that it is an ES module you need to create a package.json with a "type": "module" field or you need to rename the file to use the mjs extension as core.mjs.

That the error message here didn't give the correction information is a bug though, I've posted a fix for a better message in #35426.

@bahuwang bahuwang closed this as completed Oct 1, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants
@guybedford @bahuwang and others