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

Viewed 18325

I am super new to javascript, and a file app.js I am trying to run with npm looks like this:

import {placeOnWallComponent, wallFromFloorComponent} from './wall-from-floor'
AFRAME.registerComponent('place-on-wall', placeOnWallComponent)
AFRAME.registerComponent('wall-from-floor', wallFromFloorComponent)

And when I change the file type to app.mjs instead of app.js, I get another error: "Must use import to load ES Module."

I also have this as my package.json

{
  "name": "src",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "@std/esm": "cjs",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.mjs"
  },
  "author": "",
  "license": "ISC"
}

How do I fix this error?

UPDATE: It's still happening even after I changed the files to .mjs. If I try having start be just 'app.mjs' instead of 'node app.js', I get:

'this file does not have an app associated with it'

2 Answers

Add

"type": "module"

in your package.json

change file extensions ".js" to ".mjs" and try again the command

node --experimental-modules app.mjs

This is wrong "@std/esm": "cjs",

@std/esm is depecated. Remove this and run npm install esm on the commandline to install the esm package instead.

Adjust your load script to "start": "node -r esm app.mjs" to load esm when your app runs.

Related