简体   繁体   中英

How to use babel-core/register for writing ES6 code in node.js?

I was looking at this StackOverflow post which described how to use ES6 modules for production in Node. I tried replicating it, but for some reason something is going wrong.

Here is my app.js file:

import express from 'express'
const app = express()

app.get('/', (req, res) => {
  res.send('Hello!')
})

export default app

And here is my server.js :

require('babel-core/register')
const app = require('./app.js')
const port = 3000

app.set('port', port)

app.listen(port, () => {
  console.log(`Server listening on port ${app.get('port')}...`)
})

I thought I followed that post accurately, but I'm getting an error that says

TypeError: app.set is not a function

I imagine this is because my app isn't being exported properly, but I don't get why that's the case. Any help would be appreciated! I am using Babel6 btw, and I have the es2015 preset being used.

EDIT: It seems to work if I change export default app to module.exports = app ... that's strange

Babel 6 does not support 'export default' anymore (Babel 5 did). You have to use this Babel plugin:

https://www.npmjs.com/package/babel-plugin-add-module-exports

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM