如何使用 nodemon 运行 ECMAScript(mjs 文件)?

bol*_*hiy 5 node.js nodemon mjs

我可以使用--experimental-modules标志运行带有 nodejs 的 mjs 文件。

node --experimental-modules index.mjs
Run Code Online (Sandbox Code Playgroud)

包.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"
    }
}
Run Code Online (Sandbox Code Playgroud)

和 index.mjs

{
    "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"
    }
}
Run Code Online (Sandbox Code Playgroud)

但如果我尝试



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}`)
})

Run Code Online (Sandbox Code Playgroud)

或(在全局安装 nodemon)

npm run dev
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

nodemon index.mjs
Run Code Online (Sandbox Code Playgroud)

那么,如何在 nodemon 中启用对 ECMAScript 的支持?或者我应该使用类似esm 的东西?

Adi*_*iii 9

当然是的,你只需要稍微修改一下你的package.json

  "scripts": {
        "dev": "nodemon --experimental-modules index.mjs"
    },
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述