Esm: "ReferenceError: require is not defined" in imported *.mjs file

Created on 2 Jan 2019  路  4Comments  路  Source: standard-things/esm

I'm not sure how to configure esm to keep require & module defined in *.mjs files.

I tried setting { cjs: true, force: true }, but that does not seem to fix the error. I don't seem to understand the options & I tried almost every combination. What am I doing wrong?

question

All 4 comments

Hi @btakita!

This is by design to avoid providing a false sense of comfort with the state of experimental .mjs support in Node. The doc note on it is:

:lock: .mjs files are limited to basic functionality without support for esm options.

If you're wanting better interop you'll want to use .js and you get it out-of-the-box without having to provide extra options.

Thank you. I tried moving the require & import into a *.js file & got the following error: Error: Cannot load ES module from .mjs:

I just don't see how the *.js & *.mjs interop would work. This does work with rollup & webpack, however.

Is there any chance that we can have an option to relax the restriction for having require in *.mjs files? I'd rather be less pedantic to get my libraries working with my *.js scripts (which require *.mjs) being called using node. I can always update my code when the platform & libraries evolve.


edit: I have to call require in my mjs file due to this issue: https://github.com/aws/aws-sdk-js/issues/1769

I can always use rollup for everything, however this is inconvenient when adding a one-off *.js script that loads *.mjs.

I just don't see how the *.js & *.mjs interop would work.

Oh I meant you need to rename your .mjs file to .js. Files that use .mjs run under strict rules that align with current experimental support in Node. As such, it's very limited in terms of interop. Your best bet for interop is to not use .mjs and stick with .js for your ES modules. You'll find it easier to work with in esm and bundlers to boot.

I just don't see how the *.js & *.mjs interop would work.

Oh I meant you need to rename your .mjs file to .js. Files that use .mjs run under strict rules that align with current experimental support in Node. As such, it's very limited in terms of interop. Your best bet for interop is to not use .mjs and stick with .js for your ES modules. You'll find it easier to work with in esm and bundlers to boot.

Hey @jdalton this detailed information would be super-helpful on the README of esm and would save folks like me a lot of google searching and trying to understand why esm is treating .mjs files differently than expected.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

clock157 picture clock157  路  3Comments

OmgImAlexis picture OmgImAlexis  路  3Comments

Pokute picture Pokute  路  3Comments

ericelliott picture ericelliott  路  3Comments

janusqa picture janusqa  路  3Comments