首页 > 解决方案 > Nodemon 在尝试使用 es6 模块时崩溃,但在 es5 上运行良好

问题描述

我正在尝试使用 es6 模块运行服务器,但每次执行时都会崩溃,并且每当我使用 es5错误消息时都可以正常工作

我已经安装了 babel 并且在我的 .babelrc 文件中有 "preset": ["env"] 但是每当我运行它时,我都会遇到 "语法错误:无效或意外的令牌"。这不是一个特定的项目,这是我正在经历的第三个项目

import http from 'http';
import express from 'express';
import logger from 'morgan';
import bodyParser from 'body-parser';

// setting up express application
const app = express();

const hostName = '127.0.0.1';
const port = 3000;
const server = http.createServer(app);

// logs request to the console
app.use(logger('dev'))

// Parse incoming data requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));

// making a request to the server
app.get('*', (req, res) => res.status(200).send({
    message: 'Welcome to the default API route',
}));

server.listen(port, hostName, () => {
    console.log(`Server running at http://${hostName}:${port}/`);
});

它应该向控制台显示“欢迎使用默认 API 路由”,但它却是一条错误消息。如果需要回购,我很乐意提供

标签: node.jsexpressbabeljses6-modules

解决方案


默认情况下,Node 运行时还不支持 ES6。您可以像这样集成它:

  1. npm i esm && npm i -D nodemon

  2. 在您的 package.json 中,将其添加到脚本中:

"start": "nodemon -r esm index.js"

(确保index.js脚本的一部分与您的服务器入口点文件的名称匹配)

  1. npm start

推荐阅读