意外的令牌提供者

时间:2016-08-24 08:27:13

标签: javascript reactjs babeljs isomorphic-javascript

我尝试创建一个同构反应应用程序, 下面是我的一些文件,当我尝试使用<Provider>时,在我的server.js内部,我收到一个错误,说出了意外的令牌。

我认为这是因为我试图在我的server.js中使用jsx,但是,我对此并不确定。

在我的index.js中,我需要require(&#39; babel-core / register&#39;)({});

是否能够转换后续的Jsx语法?我在这里错过了什么吗?

的package.json

  "main": "index.js",
  "scripts": {
    "start": "node --harmony .",
    "build": "rimraf build && cross-env NODE_ENV=production webpack --config ./webpack.production.config.js --progress --profile --colors",

index.js

'use strict';

require('babel-core/register')({});
require('babel-polyfill');

var server = require('./server').default;

const PORT = process.env.PORT || 3000;

server.listen(PORT, function () {
  console.log('Server listening on: ' + PORT);
});

server.jsx

var webpack = require('webpack')
var webpackDevMiddleware = require('webpack-dev-middleware')
var webpackHotMiddleware = require('webpack-hot-middleware')
var config = require('./webpack.config')
var serveStatic = require('serve-static');
var path = require('path');
var bodyParser = require('body-parser');
var app = new (require('express'))()
var express = require('express');
var request = require('request');
import React from 'react'
import createLocation            from 'history/lib/createLocation';
import { renderToString }        from 'react-dom/server'
import { RoutingContext, match } from 'react-router';
import { Provider }              from 'react-redux';
import routes from './src/routes'


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


var isDeveloping = process.env.NODE_ENV !== 'production';
var port = isDeveloping ? 7000 : process.env.PORT;


if(isDeveloping){
  const compiler = webpack(config);
  const middleware = webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
    contentBase: 'src',
    stats: {
      colors:true,
      hash: false,
      timings:true,
      chunks:false,
      chunkModules:false,
      modules: false
    }
  });

  app.use(middleware);
  app.use(webpackHotMiddleware(compiler));
}
app.use(express.static(__dirname + '/build'));
app.use((req, res) => {
  const location = createLocation(req.url);
  const reducer  = combineReducers(reducers);
  const store    = createStore(reducer);

  match({ routes, location }, (err, redirectLocation, renderProps) => {
    if (err) {
      console.error(err);
      return res.status(500).end('Internal server error');
    }
    if (!renderProps) return res.status(404).end('Not found.');

    const InitialComponent = (
      <Provider store={store}>
        <RoutingContext {...renderProps} />
      </Provider>
    );

    // const initialState = store.getState();

    const componentHTML = renderToString(InitialComponent);
    const HTML = `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Isomorphic Redux Demo</title>
          <script type="application/javascript">
          </script>
      </head>
      <body>
        <div id="react-view">${componentHTML}</div>
        <script type="application/javascript" src="/bundle.js"></script>
      </body>
  </html>
`
    res.end(HTML);
  });
});


export default app;

webpack.config

var path = require('path')
var webpack = require('webpack')
var autoprefixer = require('autoprefixer')
var ExtractTextPlugin = require('extract-text-webpack-plugin')

var assetPath = '/assets/'
var absolutePath = path.join(__dirname, 'build', assetPath)

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    path.join(__dirname, 'src/index.js')
  ],
  output: {
    path: absolutePath,
    filename: 'bundle.js',
    publicPath: assetPath
  },
  plugins: [
    new webpack.DefinePlugin({
    'process.env':{
      'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new ExtractTextPlugin("bundle.css")
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader:  'babel' ,
        exclude: /node_modules/,
        include: [
          path.join(__dirname, 'src'),
          path.join(__dirname, 'settings')
        ],
        query: {
          presets: ['es2015']
        }
      },
      // fonts and svg
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
      {
        // images
        test: /\.(ico|jpe?g|png|gif)$/,
        loader: "file"
      },
      {
        // for some modules like foundation
        test: /\.scss$/,
        exclude: [/node_modules/], // sassLoader will include node_modules explicitly
        loader: ExtractTextPlugin.extract("style", "css!postcss!sass?outputStyle=expanded")
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract("style", "css!postcss")
      }
    ]
  },
  postcss: function(webpack) {
    return [
      autoprefixer({browsers: ['last 2 versions', 'ie >= 9', 'and_chr >= 2.3']})
    ]
  },
  sassLoader: {
    includePaths: [path.resolve(__dirname, "node_modules")]
  }
}

1 个答案:

答案 0 :(得分:4)

我遇到了类似的问题,使用这些预设创建.babelrc文档解决了我的问题:

{
  "presets": ["env", "react"]
}