在写一个react服务器渲染栗子的时候,出现nodemon编译server.jsx 抛出异常?

图片描述


package.json文件中

"scripts": {

"test": "webpack-dev-server --hot",
"server":"nodemon server.jsx --exec babel-node"

},


server.jsx
具体代码为

import express from 'express'
import React from 'react'
import { renderToString } from 'react-dom/server'
import {RoutingContext,match} from 'react-router'
import {Provider} from 'react-redux'
import * as test from '../../actions/test/testaction'
import routes from './routes'
import configureStore from './stores/index.js'

const app=express()

function renderFullPage(html,initialState){
  return (`
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8" />
    </head>
    <body>
      <div id="app">
        <div>
          ${html}
        </div>
      </div>
      <script>
        window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
      </script>
      <script src="index.js"></script>
    </body>
    </html>`
  )
}
app.use((req, res) => {
  match({ routes, location: req.url }, (err, redirectLocation, renderProps) => {
    if (err) {
      res.status(500).end(`Internal Server Error ${err}`);
    } else if (redirectLocation) {
      res.redirect(redirectLocation.pathname + redirectLocation.search);
    } else if (renderProps) {
      const store = configureStore();
      const state = store.getState();

      Promise.all([
        store.dispatch(test.getTestDate())     //store.dispatch(fetchItem(renderProps.params.id))
      ])
      .then(() => {
        const html = renderToString(
          <Provider store={store}>
            <RoutingContext {...renderProps} />
          </Provider>
        )
        res.end(renderFullPage(html, store.getState()));
      });
    } else {
      res.status(404).end('Not found');
    }
  });
});

这是自己按照教程写的一个小栗子,但是不知道为什么会出现这个错误

阅读 2.4k
2 个回答

目测是缺少 babel-preset-react,检查下.babelrc吧。

我在项目目录下没有.babelrc文件,后来新建了一个.babelrc就可行了

{
  "presets": [
    "es2015",
    "react"
  ],
  "plugins": [
    "syntax-class-properties",
    "syntax-decorators",
    "syntax-object-rest-spread",

    "transform-class-properties",
    "transform-decorators-legacy",
    "transform-object-rest-spread"
  ],
  "env": {
    "start": {
      "plugins": [
        [
          "react-transform", {
            "transforms": [
              {
                "transform": "react-transform-hmr",
                "imports": ["react"],
                "locals": ["module"]
              }
            ]
          }
        ]
      ]
    }
  }
}

谢谢楼上

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题