如何使用Nodemon运行ECMAScript(MJS文件)?

时间:2019-07-11 23:20:53

标签: node.js nodemon mjs

我可以使用--experimental-modules标志与nodejs一起运行mjs文件。

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"
    }
}

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

但是,如果我尝试

npm run dev

或(已在全球范围内安装nodemon)

nodemon index.mjs

我收到此错误

[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

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

1 个答案:

答案 0 :(得分:1)

场外yes,您只需要稍微修改一下package.json就可以

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

enter image description here