Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ES6 modules in Express

Is there a way to

  1. write my code using ES6 modules in Express app;
  2. without reverting to babel or @std/esm ?

once I am committed to app.js of Express, I can't find a way to get out of it.

This seems like something that should be already on the web, but all I can find is above options (transpiling, esm).

like image 716
Giorgi Sh. Avatar asked Dec 07 '25 01:12

Giorgi Sh.


1 Answers

With node.js, you HAVE to tell it that your main file you are loading is an ESM module. There are a couple ways to do that. The simplest is to just give the main file a .mjs file extension.

// app.mjs

import express from 'express';

const app = express();

app.get("/", (req, res) => {
    res.send("hello");
});

app.listen(80);

Then, start your program with:

node app.mjs

This works - I just ran it with node v14.4.0:. The others ways to do it are discussed in the link I previously gave you here. Per that documentation, there are three ways to specify you are loading an ESM module as the top-level module file:

  1. Files ending in .mjs.

  2. Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".

  3. Strings passed in as an argument to --eval, or piped to node via STDIN, with the flag --input-type=module.

like image 52
jfriend00 Avatar answered Dec 08 '25 13:12

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!