Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

服务端使用ES6语法 #3

Open
lensh opened this issue Jul 23, 2017 · 0 comments
Open

服务端使用ES6语法 #3

lensh opened this issue Jul 23, 2017 · 0 comments

Comments

@lensh
Copy link
Owner

lensh commented Jul 23, 2017

如何在服务端使用ES6?
不需要使用babel转码以及一系列的配置,只需要将node升级到V8版本,V8已经很好地支持了ES6/ES7/ES8等最新特性,这是目前最好的办法。升级到V8版本,可以直接到nodejs中文网(http://nodejs.cn/download/) 下载即可。
升级到V8后,可能还不支持通过import/export关键字来导入导出模块(服务端已经有了CommonJS规范,即使用require/exports关键字来导入导出模块),你可以继续使用module.exports来导出模块,如果一定要用import/export,那么这时可以在文件入口添加以下代码:

require("babel-core/register")({
  presets: ['es2015', 'stage-0']
})
require("babel-polyfill")

同时需要通过npm安装babel-core、babel-preset-es2015、babel-preset-stage-0、babel-polyfill等依赖。
这样就可以愉快地使用import/export了。
项目中服务端代码片段:

import express from 'express'
import loginRouter from './router/login'
import registerRouter from './router/register'
import friendRouter from './router/friend'
import messageRouter from './router/message'
import userRouter from './router/user'
import chatRouter from './router/chat'

const apiRouter = express.Router()

apiRouter
	.use('/login', loginRouter)
	.use('/register', registerRouter)
	.use('/friend', friendRouter)
	.use('/message', messageRouter)
	.use('/user', userRouter)
	.use('/chat', chatRouter)

export default apiRouter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant