运行节点server.js会引发语法错误

时间:2016-10-31 13:42:28

标签: node.js express reactjs

我有我的基本server.js:

var express = require('express');
var path = require('path');
var port = process.env.PORT || 8080;
var app = express();

app.use(express.static('src/client/'));

app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname + '/src/client/index.html'))
});

app.listen(port);
console.log('server started');

但是我现在有一个我要导入的react-routing,这样当浏览器在服务器上刷新时,页面仍然可以访问。

到目前为止,我的尝试是:

import express from 'express';
import path from 'path';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import routes from './src/client/app/config/routes.jsx';

let port = process.env.PORT || 8080;
let app = express();

app.use(express.static('src/client/'));

// app.get('/', (req, res) from> {
//  res.sendFile(path.resolve(__dirname + '/src/client/index.html'))
// });

app.get('/', (req, res) => {
  match(
    { routes, location: req.url },
    (err, redirectLocation, renderProps) => {

      // in case of error display the error message
      if (err) {
        return res.status(500).send(err.message);
      }

      // in case of redirect propagate the redirect to the browser
      if (redirectLocation) {
        return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
      }

      // generate the React markup for the current route
      let markup;
      if (renderProps) {
        // if the current route matched we have renderProps
        markup = renderToString(<RouterContext {...renderProps}/>);
      } 
      // else {
      //   // otherwise we can render a 404 page
      //   markup = renderToString(<NotFoundPage/>);
      //   res.status(404);
      // }

      // render the index template with the embedded React markup
      return res.render(path.resolve(__dirname + '/src/client/index.html'));
    }
  );
});

app.listen(port);
console.log('server started');

但是当我运行&#34;节点server.js&#34;我收到以下错误:

(function (exports, require, module, __filename, __dirname) { import express from 'express';
                                                              ^^^^^^
SyntaxError: Unexpected reserved word

1 个答案:

答案 0 :(得分:0)

除了import / export关键字之外,ES6中的所有内容都适用于新版本的节点。您必须使用gulp,webpack等将其转换为ES5。