require('babel/register') doesn't work

2019-01-11 05:39发布

I have isomorphic app written in ES6 on client with Babel transpiler. I want my express server to have the same ES6 syntax as client code.

Unfortunately require('babel/register') doesn't work..

server.js

require('babel/register'); // doesn't work
// require('babel-core/register); doesn't work..

const env = process.env.NODE_ENV || 'development';
const port = process.env.NODE_PORT || 1995;

const http = require('http');
const express = require('express');
const address = require('network-address');

let app = express();

app.set('port', port);
app.use(express.static(path.join(__dirname, 'public')));

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

http.createServer(app).listen(app.get('port'), function () {
   console.info('Demo app is listening on "%s:%s" env="%s"', address(), app.get('port'), env);
});

8条回答
Viruses.
2楼-- · 2019-01-11 06:30

require('babel/register') doesn't transpile the file it is called from. If you want server.js to be included in on-the-fly transpilation, you should execute it with babel-node (Babel's CLI replacement for node).

See my answer here for an example.

查看更多
Melony?
3楼-- · 2019-01-11 06:34

steps to fix this:

  1. remove require('babel/register'); from server.js
  2. create another entry file called start.js
  3. in start.js,

    require('babel/register'); module.exports = require('./server.js');

The result is that all code inside server.js will be transpiled on the fly by the register. Please make sure you have configured babel correctly with a .babelrc having the content like below

{
  "presets": ["es2015", "stage-0"]
}
查看更多
登录 后发表回答