Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run ECMAScript (mjs files) with nodemon?

I am able to run mjs files with nodejs using --experimental-modules flag.

node --experimental-modules index.mjs

package.json:

{
    "name": "mjs-tests",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "dev": "nodemon index.mjs"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "chalk": "^2.4.2",
        "uuid": "^3.3.2"
    },
    "devDependencies": {
        "nodemon": "^1.19.1"
    }
}

And index.mjs



import http from 'http'

const server = http.createServer((req, res) => {
    res.end('hello')
})

const PORT = 5000
server.listen(PORT, () => {
    console.log(`πŸƒβ€β™€οΈ Server is running at http://localhost:${PORT}`)
})

But if I try to

npm run dev

or (with nodemon installed globally)

nodemon index.mjs

I get this error

[nodemon] 1.19.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.mjs`
internal/modules/cjs/loader.js:821
  throw new ERR_REQUIRE_ESM(filename);
  ^

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

So, How I can enable support for ECMAScript in nodemon? Or should I use something like esm?

like image 586
boleeluchshiy Avatar asked Jul 11 '19 23:07

boleeluchshiy


People also ask

What kind of file is MJS?

mjs extension is a JavaScript source code file that is used as an ECMA Module (ECMAScript Module) in Node. js applications. Node. js's natvie module system is CommonJS that is used to split the code in different files to keep the JS code organized.

How can ECMAScript be used natively in node?

Enabling# Node.js has two module systems: CommonJS modules and ECMAScript modules. Authors can tell Node.js to use the ECMAScript modules loader via the .mjs file extension, the package.json "type" field, or the --input-type flag. Outside of those cases, Node.js will use the CommonJS module loader.


1 Answers

Offcourse yes, All you need to modify your package.json a bit

  "scripts": {
        "dev": "nodemon --experimental-modules index.mjs"
    },

enter image description here

like image 119
Adiii Avatar answered Oct 23 '22 20:10

Adiii