1、參考koa+react(一)
http://blog.suzper.com/2016/10/19/koa-react-%E4%B8%80/
為了使用 KOA2 能夠運行,必須能夠使用ES7語法 async/await 能夠編譯,需要借用 babel 的能力。使用最新版本 V6。
1、安裝Node (V6或者V7)創建一個項目目錄
md koa2pro , cd koa2pro ; 初始化 node ini 產生一個 package.json 文件
2、安裝 koa2包: npm install --save koa@next
3、babel V6 必須安裝下列包:
npm install --save-dev babel-core babel-register babel-polyfill
npm install --save-dev react 后面要使用,先安裝上。
配置 babel 參數:
使用一個 .babelrc 文件,增加下列配置項:latest 設置 = es2015 + ea2016 + es2017 三者之和。
{
"presets": ["latest", "react"]
}
4、建立兩個啟動文件:
index.js
-----------------------------
require("babel-register");
require("babel-polyfill"); //引入這個文件babel-polyfill很重要,否則出現錯誤
require("./main.js");
main.js
-----------------------------
import Koa from 'koa';
const app = new Koa();
app.use(async (ctx, next) => {
const start = new Date();
await next();
const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
// response
app.use((ctx) => {
ctx.body = 'Hello Koa in app-async.js';
});
app.listen(3000); 或者 app.listen(3000, () => console.log('系統啟動,端口:3000'))
console.log("系統啟動,端口:3000");
=============================
使用: node index.js 可以運行了。 這種方式,不能看到編譯后的代碼。
5、使用命令行方式:
如果想使用命令行編譯(不是自動編譯),可以安裝 :
npm install --save-dev babel-cli
然后在package.json 中加上:
"scripts": {
"build": "babel src -d lib"
},
需要建立兩個目錄 src 源代碼目錄,lib 編譯后代碼目錄。將上面的兩個文件 index.js main.js 移動至 src目錄。
使用: npm run build 命令行,就可以在 lib 下看到編譯成果了。
兩種代碼都可以運行了: node src\index.js 或者 node lib\index.js
6、繼續安裝 nodemon
npm install -g nodemon 全局安裝
現在可以使用 nodemon 起動 : nodemon
它會在 package.json 中尋找 "main": "./lib/index.js" 項中配置。作為啟動文件。
7、其它;;;
如果 配置 babel 參數,在.babelrc 文件 。
{
"presets": ["es2015", "react"]
}
在Node7 下,必須使用 node --harmony index.js 才能使用代碼中的: async/await
