javascript - Unexpected token Provider - Stack Overflow

I'm trynig to create an isomorphic react application, Below are some of my files, Inside my serve

I'm trynig to create an isomorphic react application, Below are some of my files, Inside my server.js when I try to use <Provider>, I get an error saying Unexpected token.

I assume this is because I'm trying to use jsx inside my server.js, But, I'm not sure on this.

Inside my index.js, I have required require('babel-core/register')({});

Won't this be able to transpile the subsequnt Jsx syntax? Am I missing something here?

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 piler = webpack(config);
  const middleware = webpackDevMiddleware(piler, {
    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(piler));
}
app.use(express.static(__dirname + '/build'));
app.use((req, res) => {
  const location = createLocation(req.url);
  const reducer  = bineReducers(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 ponentHTML = 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">${ponentHTML}</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")]
  }
}

I'm trynig to create an isomorphic react application, Below are some of my files, Inside my server.js when I try to use <Provider>, I get an error saying Unexpected token.

I assume this is because I'm trying to use jsx inside my server.js, But, I'm not sure on this.

Inside my index.js, I have required require('babel-core/register')({});

Won't this be able to transpile the subsequnt Jsx syntax? Am I missing something here?

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 piler = webpack(config);
  const middleware = webpackDevMiddleware(piler, {
    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(piler));
}
app.use(express.static(__dirname + '/build'));
app.use((req, res) => {
  const location = createLocation(req.url);
  const reducer  = bineReducers(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 ponentHTML = 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">${ponentHTML}</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")]
  }
}
Share Improve this question asked Aug 24, 2016 at 8:27 nitte93nitte93 1,8483 gold badges28 silver badges42 bronze badges 3
  • Does your package.json have dependency for react-redux? – Rishikesh Dhokare Commented Aug 24, 2016 at 10:15
  • Hi, thanks for responding. Yes it has. I believe I'm missing something with the transpiler nad it's Isomorphic implementation. – nitte93 Commented Aug 24, 2016 at 11:34
  • 1 is there .babelrc file with presets defined for es2015 and react? – Rishikesh Dhokare Commented Aug 29, 2016 at 3:24
Add a ment  | 

1 Answer 1

Reset to default 6

I had a similar problem and creating a .babelrc document with these presets solved my problems:

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745341297a4623338.html

相关推荐

  • javascript - Unexpected token Provider - Stack Overflow

    I'm trynig to create an isomorphic react application, Below are some of my files, Inside my serve

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信