Setup Babel ES6 for Express and Nodejs

wooHsi / 2024-07-17 / 原文

Create project and install dependencies

mkidr my-app && cd my-app
npm init -y
npm i -D @babel/cli @babel/core @babel/node @babel/preset-env dotenv
npm i expresss

Create .babelrc

{
    "presets": ["@babel/preset-env"]
}

Write a web service

mkdir src/ && touch src/app.js

In app.js

import express from 'express';

const app = express()
const port = 9098

app.get('/', (req, res) => {
    res.send('ok')
})
app.listen(port, () => {
    console.log(`app listen on port ${port}`)
})

package.json

Include "type": "module" at the root level and add the start script "start": "npx nodemon --exec babel-node src/app.js" inside the scripts section.

{
  "name": "my-app",
  "version": "1.0.0",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "npx nodemon -r dotenv/config --exec babel-node src/app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "express": "^4.19.2"
  },
  "devDependencies": {
    "@babel/cli": "^7.24.8",
    "@babel/core": "^7.24.9",
    "@babel/node": "^7.24.8",
    "@babel/preset-env": "^7.24.8"
  }
}

Start the project

npm start
curl http://localhost:9098/