虽然Nodejs支持ES6特性越来越完整,但是很可惜模块部分仍然不支持。目前可以通过babel来解决 。
创建项目,并安装相关依赖
{
"name": "nodees6",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.25.0",
"babel-preset-es2015": "^6.24.1",
"babel-register": "^6.24.1"
}
}
{
"presets":['es2015']
}
require('babel-register')
require('./nodees6.js')
采用bebel register实时转译代码。
创建nodees6.js
import http from "http"
const server = http.createServer((req, res)=>{
console.log(req.url)
res.write("hello the world")
res.end()
})
server.listen(9001)
curl http://localhost:9001/hello?user=chf
当然也可以模块部分采用原有的写法,其它可以直接使用ES6的语法。
const http = require('http')
const server = http.createServer((req, res)=>{
console.log(req.url)
res.write("hello the world")
res.end()
})
server.listen(9001)
最终效果也是一样的。