简体   繁体   English

如何使用babel-core / register在node.js中编写ES6代码?

[英]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. 我在看这个 StackOverflow帖子,它描述了如何在Node中使用ES6模块进行生产。 I tried replicating it, but for some reason something is going wrong. 我尝试复制它,但是由于某种原因出现了问题。

Here is my app.js file: 这是我的app.js文件:

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

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

export default app

And here is my server.js : 这是我的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 TypeError:app.set不是函数

I imagine this is because my app isn't being exported properly, but I don't get why that's the case. 我想这是因为我的app未正确导出,但我不知道为什么会这样。 Any help would be appreciated! 任何帮助,将不胜感激! I am using Babel6 btw, and I have the es2015 preset being used. 我正在使用Babel6 btw,并且正在使用es2015预设。

EDIT: It seems to work if I change export default app to module.exports = app ... that's strange 编辑:如果我将export default app更改为module.exports = app ...,这似乎很有效。这很奇怪

Babel 6 does not support 'export default' anymore (Babel 5 did). Babel 6不再支持“导出默认值”(Babel 5支持)。 You have to use this Babel plugin: 您必须使用以下Babel插件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在使用 babel 或 webpack 的 ES6 导入/导出模块中使用 Node.js CommonJS 模块? - How can I use Node.js CommonJS modules in ES6 import/export modules using babel or webpack? 我可以在没有Babel的Node.js中使用ES6 Javascript吗? - Can I use ES6 Javascript in Node.js without Babel? 如何改进Node.js中的分配代码(ES6样式) - How to Improve Assignment Code in Node.js (ES6 style) babel-cli vs babel-preset-es2015 vs babel-register vs babel-core? - babel-cli vs babel-preset-es2015 vs babel-register vs babel-core? 'babel-core / register'vs'babel-register' - 'babel-core/register' vs 'babel-register' Babel成功地转译了ES6代码(node.js),但是当“ npm start”执行时,它会抛出“ SyntaxError:意外的令牌导入” - Babel transpiled ES6 code (node.js) successfully, but when do “npm start” it throws “SyntaxError: Unexpected token import ” 使用VSCode调试node.js ES6代码 - Debugging node.js ES6 code with VSCode 什么时候在Node.js ES6中的Promise中启动代码? - When start code in Promise in Node.js ES6? 如何在不转译代码的情况下在 Visual Studio Code 中使用 ES6 模块调试 Node.JS? - How to debug Node.JS with ES6 modules in Visual Studio Code without transpiling the code? 2019 年在 Node.js 和 Babel 中使用 ES6 模块(导入、导出) - Using ES6 modules (import, export) in Node.js with Babel in 2019
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM