搭建node的項目並支持ES6寫法

如今ES6在前端開發中已經很是普及了,因此前端轉向node開發還能夠繼續保持ES6寫法,如今node對ES6語法友好度愈來愈高,下面咱們開始搭建一個支持ES6寫法的node項目。同時使用nodemon配置項目源碼修改時自動重啓服務。前端

首先要初始化一個項目node

npm init
或
npm init -y

先安裝一個express(根據本身的需求選擇web服務框架)mysql

npm install express --save

安裝babel工具web

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/runtimesql

npm install @babel/runtime --save

安裝 nodemon NODE項目代碼修改時咱們須要讓項目自動編譯更新express

npm install nodemon --save-dev

安裝 「rimraf」 項目文件打包時須要刪除上次打包的文件目錄npm

npm install rimraf --save-dev

cross-env能跨平臺地設置及使用環境變量json

npm install cross-env --save

下面咱們配置一下package.json文件,在scripts中添加下面的代碼api

"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')

到此就結束了,這是我項目中最基本的配置

相關文章
相關標籤/搜索