Did*_*ayo 3 node.js express babeljs es6-modules
我正在尝试使用 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}/`);
});
Run Code Online (Sandbox Code Playgroud)
它应该向控制台显示“欢迎使用默认 API 路由”,但实际上这是一条错误消息。如果需要回购,我很乐意提供
默认情况下,Node 运行时尚不支持 ES6。您可以像这样集成它:
npm i esm && npm i -D nodemon
在 package.json 中,将其添加到脚本中:
"start": "nodemon -r esm index.js"
(确保index.js脚本的部分与您的服务器入口点文件的名称匹配)
npm start