开始准备
首先安装babel-cli
$ npm install --save-dev babel-cli
然后添加一些presets
$ npm install --save-dev babel-preset-es2015 babel-preset-stage-2
再新建index.js文件,写些代码。
$ touch index.js
import http from 'http';http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n');}).listen(1337, '127.0.0.1');console.log('Server running at http://127.0.0.1:1337/');
然后,在package.json中加上npm start脚本
"scripts": {
+ "start": "babel-node index.js --presets es2015,stage-2"
}
现在,让我们启动服务器
$ npm start
现在,你可以在浏览器中访问http://127.0.0.1:1337/,并且看到hello world
使用nodemon监听文件的修改
我们能够使用nodeman来改善npm start脚本
$ npm install --save-dev nodemon
然后,我们再更新npm start脚本
"scripts": {
- "start": "babel-node index.js"
+ "start": "nodemon index.js --exec babel-node --presets es2015,stage-2"
}
然后,我们重启服务器
$ npm start
现在,你可以修改index.js中的代码,我们的服务器能够通过nodemon来自动重启。
在服务器运行的过程中,修改Index.js中的代码,将Hello World改为Hi man
如果你现在访问http://127.0.0.1:1337,你会看到服务器的欢迎语已经变成Hi man了。
在产品模式下运行
在产品模式下运行,我们要先编译下代码。
首先,我们将index.js文件,移到lib/index.js
$ mv index.js lib/index.js
并且,要更新npm start脚本中index.js文件的路径
"scripts": {
- "start": "nodemon index.js --exec babel-node --presets es2015,stage-2"
+ "start": "nodemon lib/index.js --exec babel-node --presets es2015,stage-2"
}
接下来,添加两个任务,npm run build和npm run serve
"scripts": {
"start": "nodemon lib/index.js --exec babel-node --presets es2015,stage-2",
+ "build": "babel lib -d dist --presets es2015,stage-2",
+ "serve": "node dist/index.js"
}
现在,我们能运行npm run build命令来编译我们的代码,然后,运行npm run serve命令在产品模式下启动我们的服务器
$ npm run build
$ npm run serve
我们可以新建个.gitignore文件来忽略dist目录
$ touch .gitignore
在.gitignore文件中,加上
dist
这可以确保我们不会提交编译后的代码到git
保存Babel Options到.babelrc
让我们创建一个.babelrc文件
$ touch .babelrc
然后在.babelrc中添加如下内容
{
"presets": ["es2015", "stage-2"],
"plugins": []
}
现在,我们可以删除package.json中的options
"scripts": {
+ "start": "nodemon lib/index.js --exec babel-node",
+ "build": "babel lib -d dist",
"serve": "node dist/index.js"
}
测试服务器程序
最后,让我们来为服务器写些测试脚本
首先,安装mocha
$ npm install --save-dev mocha
然后,创建文件test/index.js
$ mkdir test
$ touch test/index.js
import http from 'http';import assert from 'assert';import '../lib/index.js';describe('Example Node Server', () => { it('should return 200', done => { http.get('http://127.0.0.1:1337', res => { assert.equal(200, res.statusCode); done(); }); });});
接下来,安装babel-register 作为require钩子
$ npm install --save-dev babel-register
然后,我们能添加npm test脚本
"scripts": {
"start": "nodemon lib/index.js --exec babel-node",
"build": "babel lib -d dist",
"serve": "node dist/index.js",
+ "test": "mocha --compilers js:babel-register"
}
现在,让我们来运行我们的测试
$ npm test
你应该会看见下面的输出
Server running at http://127.0.0.1:1337/
Example Node Server
✓ should return 200
1 passing (43ms)
好了,结束。
网友评论