Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  5] [ 3]  / answers: 1 / hits: 15410  / 4 Years ago, sun, july 5, 2020, 12:00:00

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).


More From » node.js

 Answers
5

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.




[#50834] Sunday, June 21, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loganl

Total Points: 424
Total Questions: 86
Total Answers: 112

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;