8

I am trying to use ES6 on server side. I a have separated endpoint from server file:

archive.js:

import { Router } from "express";
const router = Router();

router.get("/", async (req, res) => { "some code"});

export default router;

when i want to import it to my server file like this:

import archive from "./endpoints/archive.js";
app.use("/archive", archive);

it gives me an error:

(node:9565) ExperimentalWarning: The ESM module loader is experimental. internal/modules/run_main.js:54 internalBinding('errors').triggerUncaughtException()

any idea guys? i dont want to go back to require/module.exports

A Zarqam
  • 338
  • 2
  • 3
  • 12
  • What version of nodejs? By default a `.js` file is assumed to be a CommonJS file, NOT an ESM module unless you have appropriately tagged it in a package.json file. It is much easier to get ESM modules to work by making them `.mjs` files, not `.js` files because the loader assumes any `.mjs` file is an ESM module. Which file does this warning/error occur in? – jfriend00 Aug 08 '20 at 17:00
  • This was a new directory which i have pulled from github repo. I have tried many things/solutions but it turned out i have to clone to a new directory/environment. Couldnt find the problem or a proper fix but in the new directory/environment i dont have that problem. – A Zarqam Aug 08 '20 at 21:20

2 Answers2

13

you can use Node v14.12.0; where this probleme is solved, and read this doc https://nodejs.org/api/esm.html#esm_package_json_type_field

user14345124
  • 131
  • 3
3

I realize after a few tries that "--experimental-modules" flag on the "nodemon" causes issues to realize the imports in the whole app so I did update that flag to use the new flag for explicit filenames"--es-module-specifier-resolution=node" and now works perfect here is an article about this new flag : https://nodejs.medium.com/announcing-a-new-experimental-modules-1be8d2d6c2ff

So for explane you can do a script like this:

nodemon --es-module-specifier-resolution=node

Also keep in mind the nodejs version you use a version under 12.XX, 14.XX or the last stable version.

Upgrade Node.js to the latest version on Mac OS

I hoper this helps more developers :)

Ismael Terreno
  • 1,021
  • 8
  • 5