I'm trying to implement SSR with Node.js and React following this example https://github.com/babel/example-node-server as advised in the official Babel docs here http://babeljs.io/docs/usage/cli/#babel-node
For development, I'm using babel-node
; for production I want to transpile my server with babel and run it with node
:
package.json
"scripts": {
"start": "node ./dist/server/index.js",
"dev:server": "nodemon ./src/server/index.js -x babel-node",
"build:server": "babel ./src/server -d ./dist/server --copy-files -s inline"
},
"babel": {
"presets": [
"env",
"react",
"stage-2"
],
"plugins": [
"transform-decorators-legacy"
]
}
The server is written with ES6 syntax:
src/server/index.js
import 'babel-polyfill'
import './config'
import Express from 'express'
import bootstrap from './bootstrap'
const app = Express()
bootstrap(app)
export default app
Then in some route I import my React components to render it into HTML on request:
src/server/routes/admin.js
import { Router } from 'express'
import React from 'react'
import createHistory from 'history/createMemoryHistory'
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'
import { StaticRouter, matchPath } from 'react-router'
import configureStore from '../../../src/admin/store'
import routes from '../../../src/admin/routes'
import Root from '../../../src/admin/containers/Root'
// etc.
The error is thrown when server tries to import React components
./src/admin/store/index.js:11
export default configureStore
^^^^^^
SyntaxError: Unexpected token export
I tried using babel-register
in the server, and it works, but it's not recommended to use it in production mode, so I would rather not do it.
Also, when inspecting the built server code, I find:
dist/server/routes/admin.js
var _store = require('../../../src/admin/store');
It means that it's still referencing the src
folder. Ideally I'd like to somehow incorporate those modules into the built server code, so I could safely remove the src
folder from the production environment, leaving only dist
.
Edit
Different from Babel 6 CLI: Unexpected token export?