In the previous section, I talked about using AXIos and interceptors in the Node layer, but I found that Express does not support ES6 now. The original interceptor code was written in ES6 style, so I decided to consider making Express support ES6 syntax.

Modifying the directory Structure

Switch to the node-api directory and create a new SRC folder.

  • Create the SRC/directory
  • Move bin/, app.js, and routes/ to the SRC directory
  • Rename the WWW file in the bin directory to www.js
  • Move public/ to the project root

The syntax conversion

Edit server/node_api/ SRC /bin/www.js and change the require command in the header to import

#! /usr/bin/env node /** * Module dependencies. */ import app from '.. /app' import debugLib from 'debug' import http from 'http' const debug = debugLib('node-api:server') // var app = require('.. /app'); // var debug = require('debug')('node-api:server'); // var http = require('http');Copy the code

Edit server/node_api/ SRC /routes/index.js, replace require with import, export with module.exports

// var express = require('express')
// var router = express.Router()
import express from 'express'
var router = express.Router()
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' })
})

// module.exports = router
export default router
Copy the code

Server /node_api/ SRC /routes/users.js is a file that contains route Settings, but it will be changed to axios. Update server/node_api/ SRC /app.js. Replace require with import syntax. For example app.set(‘views’, path.join(__dirname, ‘.. /views’))

import express from 'express' import path from 'path' import cookieParser from 'cookie-parser' import logger from 'Morgan' import createError from 'http-errors' import indexRouter from './routes/index' // no usersRouter import cors from 'cors' const app =express() // var app = express() // view engine setup app.set('views', path.join(__dirname, '.. /views')) app.set('view engine', 'jade') app.use(logger('dev')) app.use(express.json()) app.use(express.urlencoded({ extended: false })) app.use(cookieParser()) app.use(express.static(path.join(__dirname, '.. /public'))) app.use('/', indexRouter) // app.use('/users', // Catch 404 and forward to error handler app. Use (function (req, res, next) { next(createError(404)) }) ... // error handler app.use(function (err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message res.locals.error = req.app.get('env') === 'development' ? err : {} // render the error page res.status(err.status || 500) res.render('error') }) export default appCopy the code

The script configuration

Install npm-run-all first to increase writing convenience when running multiple scripts at a time. npm install npm-run-all –save-dev

Install Babel and other packages. Babel is a Javascript compiler that converts ECMAScript 2015+ code into backward-compatible Javascript syntax to run in current and older browsers and other environments, such as Node.js. Open the terminal command line in the project root directory and type the following command to install the latest version of Babel (Babel 7).

npm install -D @babel/core @babel/cli @babel/preset-env @babel/node

-d means installed packages are placed under devDependency –save means installed packages are placed under dependency

Babelrc writes the following code to the node-api root directory

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

Since we use Babel to convert DIFFERENT types of JS syntax, preset-env (previously installed) needs to be configured in.babelrc, which tells Babel which type to convert.

With all this set up, we can test whether Node Server can run in ES6 syntax by first adding the dev script to package.json:

  "scripts": {
     "server": "babel-node ./src/bin/www",
     "dev": "NODE_ENV=development npm run server",
    },
Copy the code

/ SRC /bin/ WWW. Run NPM dev will start normally.

Configuration nodemon

Add a watch script that automatically listens for file numbers and restarts the server through configuration files, which is more elegant. Install the nodemon NPM I -d nodemon Add the nodemon.json configuration file in the node_api root directory

{
  "exec": "npm run dev",
  "watch": ["src/*", "public/*"],
  "ext": "js, html, css, json"
}
Copy the code

Add a Watch script

  "scripts": {
    "server": "babel-node ./src/bin/www",
    "server:prod": "node ./dist/bin/www",
    "dev": "NODE_ENV=development npm run server",
    "clean": "rimraf dist",
    "build": "babel ./src --out-dir dist",
    "start": "npm run prod",
    "prod": "NODE_ENV=production npm-run-all clean build server:prod",
    "watch": "nodemon"
  },
Copy the code

Production preparation

The prod script is a little different from the dev script in that we need to convert all the js file code in the SRC directory into a syntactic form that nodeJS can recognize. Running the prod script generates a dist/ folder with a similar SRC/directory structure, but each time before running the script, we need to remove the old dist/ folder to make sure we are running the newly generated code. Here are the steps:

  • Create a build script that transforms the file code in SRC/and generates a new dist/ folder.
  • Install the Rimraf package and create a new clean script to delete the dist/ folder.
  • Create a new prod script and combine the clean, Build, and Start server scripts.

We’ll start by installing the Rimraf package to delete a folder

npm install rimraf --save

Once installed, add the clean script to the scripts field of package.json, which we will use in our build script, and the structure of the entire scripts field is as follows

"scripts": {
    "server": "babel-node ./src/bin/www",
    "server:prod": "node ./dist/bin/www",
    "dev": "NODE_ENV=development npm run server",
    "clean": "rimraf dist",
    "build": "babel ./src --out-dir dist",
    "start": "npm run prod",
    "prod": "NODE_ENV=production npm-run-all clean build server:prod"
  },
Copy the code

The original text uses ES6 (and above) syntax in Node and Express