伟大伟大

Setup Babel ES6 for Express and Nodejs

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",
    "build": "npx rimraf dist/ && babel src/ --out-dir dist/ --ignore ./node_modules,./.babelrc,./package.json,./npm-debug.log --copy-files",
    "start": "npm run build && node --env-file=.env dist/server.js",
    "dev": "npx nodemon --exec babel-node -r dotenv/config -w .env -w src -w static src/server.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/
posted @ 2024-07-17 10:28  wooHsi  阅读(6)  评论(0)    收藏  举报