Node: Error [ERR_REQUIRE_ESM]: Must use import to load ES

Created on 15 Nov 2017  路  6Comments  路  Source: nodejs/node

Question asked https://stackoverflow.com/q/47315280/2103767 trying to get node --experimental-module to work with resolve and stumbled across this.

$ node -r @std/esm apple.mjs
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\Users\user\projs\dev\my-proj\test\es2015\test\apple.mjs
    at Module.load (module.js:560:32)
    at tryModuleLoad (module.js:503:12)
    at Function.Module._load (module.js:495:3)
    at Function.Module.runMain (module.js:682:10)
    at startup (bootstrap_node.js:191:16)

apple.mjs contents

// apple.mjs
import {banana} from './banana.mjs'

banana();

export default function apple() {}

ES Modules question wrong repo

Most helpful comment

Note that that is not --experimental-modules.

If you wish to run it using node's built-in --experimental-module, you would do:

node --experimental-modules apple.mjs

All 6 comments

afaik @std/esm can't integrate with the loader to do that but cc @jdalton on that point

Hi @yogeshgadge!

This isn't really a Node issue.
In the future you can post questions like this to the @std/esm repo.

You're getting the error

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: 

because you need to opt-in to the @std/esm loader by making it a dep or by adding its options object to the package.json of apple.mjs. So after doing npm i --save @std/esm, when you run

node -r @std/esm apple.mjs

You'll get

/path/to/kale.js:1
export function kale() {}
^

SyntaxError: 'import' and 'export' may only be used in ES modules
    at /path/to/banana.mjs

This is because, by default, @std/esm follows Nodes proposed module rules.
To unlock CJS compat you simply add this option to your package.json

"@std/esm": "cjs"

Then node -r @std/esm apple.mjs will run without error.

@yogeshgadge

FWIW I've fixed the initial error message to be more helpful, so that in a future release when you don't have the @std/esm opt-in you'll get:

Error [ERR_REQUIRE_ESM]: Must opt-in @std/esm to load ES Module: ...

Note that that is not --experimental-modules.

If you wish to run it using node's built-in --experimental-module, you would do:

node --experimental-modules apple.mjs

Closing since it's not an issue with node.js core.

Sorry wrong repo.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

willnwhite picture willnwhite  路  3Comments

loretoparisi picture loretoparisi  路  3Comments

fanjunzhi picture fanjunzhi  路  3Comments

filipesilvaa picture filipesilvaa  路  3Comments

akdor1154 picture akdor1154  路  3Comments