搭建node的项目并支持ES6写法

现在ES6在前端开发中已经非常普及了,所以前端转向node开发还可以继续保持ES6写法,现在node对ES6语法友好度越来越高,下面我们开始搭建一个支持ES6写法的node项目。同时使用nodemon配置项目源码修改时自动重启服务。

首先要初始化一个项目

npm init
或
npm init -y

先安装一个express(根据自己的需求选择web服务框架)

npm install express --save

安装babel工具

npm install babel-cli --save-dev
npm install babel-plugin-transform-runtime --save-dev
npm install babel-preset-env --save-dev
npm install babel-preset-es2015 --save-dev
npm install babel-preset-latest --save-dev
npm install babel-register --save-dev

安装@babel/runtime

npm install @babel/runtime --save

安装 nodemon NODE项目代码修改时我们需要让项目自动编译更新

npm install nodemon --save-dev

安装 “rimraf” 项目文件打包时需要删除上次打包的文件目录

npm install rimraf --save-dev

cross-env能跨平台地设置及使用环境变量

npm install cross-env --save

下面我们配置一下package.json文件,在scripts中添加下面的代码

"build": "rimraf dist/ && babel ./ --out-dir dist/ --ignore ./node_modules,./.babelrc,./package.json,./npm-debug.log --copy-files",
"start": "cross-env NODE_ENV=development nodemon --harmony index-api.js"

然后新建一个文件.babelrc,将下面的代码写进入

{
  "presets": ["es2015"],
  "plugins": ["transform-runtime"]
}

到此基本的配置已经完成了,下面建立一个服务器文件 app.js

import express from 'express'
const app = express()
app.listen(3000, function() {
    console.log('服务器启动成功!')
})

此时如果急用node命令启动app.js会出现错误,因为import模块引入命令node不认,所以要用一个中间页面做一下过渡
新建一个index.js

require('babel-register') ({
  presets: [ 'env' ]
})
require('./app.js')

此时用npm start index.js启动项目(用node命令直接启动index.js文件也不会报错了)

下面我把我项目中的配置贴出来仅供大家参考

package.json文件

{
  "name": "node-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "rimraf dist/ && babel ./ --out-dir dist/ --ignore ./node_modules,./.babelrc,./package.json,./npm-debug.log --copy-files",
    "start": "cross-env NODE_ENV=development nodemon --harmony index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/runtime": "^7.4.2",
    "cookie-parser": "^1.4.4",
    "cross-env": "^5.2.0",
    "express": "^4.16.4",
    "express-session": "^1.15.6",
    "mysql": "^2.16.0",
    "node-uuid": "^1.4.8"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-latest": "^6.24.1",
    "babel-register": "^6.26.0",
    "nodemon": "^1.18.10",
    "rimraf": "^2.6.3"
  }
}

.babelrc

{
  "presets": ["es2015"],
  "plugins": ["transform-runtime"]
}

app.js

import express from 'express'
import router from './router/index.js'
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
import session from 'express-session';
const app = express();
app.set('port', process.env.PORT || 200); // 设定监听端口

app.all('*', (req, res, next) => {
  const { origin, Origin, referer, Referer } = req.headers;
  const allowOrigin = origin || Origin || referer || Referer || '*';
    res.header("Access-Control-Allow-Origin", allowOrigin);
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials", true); //可以带cookies
    res.header("X-Powered-By", 'Express');
    if (req.session) {
        console.log('进入')
        
    }
    if (req.method == 'OPTIONS') {
      res.sendStatus(200);
    } else {
    next();
    }
});

app.use(express.static('./view'));
app.use(bodyParser.json({limit: '1mb'}));  // 这里指定参数使用 json 格式
app.use(cookieParser());     // 挂载cookie
app.set('trust proxy', 1)
app.use(session({
    secret: 'keyboardcat',
    name: 'token',   //这里的name值得是cookie的name,默认cookie的name是:connect.sid
    rolling: true,
    cookie: {maxAge: 60 * 60 * 1000 , httpOnly:true},  //设置maxAge是80000ms,即80s后session和相应的cookie失效过期
    resave: true,
    saveUninitialized: false
}));

router(app);

app.listen(app.get('port'), () => {
  console.log(`服务端口:${app.get('port')}`)
})

index.js

require('babel-register') ({
  presets: [ 'env' ]
})
require('./app.js')

到此就结束了,这是我项目中最基本的配置

你可能感兴趣的:(express,node.js)