在routes.js处导入意外的令牌

时间:2017-03-25 10:10:15

标签: javascript reactjs react-router jsx

我正在努力学习react + express。这是我正在关注的文件夹结构。

app
 -client
   -components
     -home.jsx
 -nodemodules
 -server
 -config.js        
 -package.json
 -routes.js

** Package.json:

{
  "name": "job-application",
  "version": "1.0.0",
  "description": "making a website using MERN ",
  "main": "nodemon config.js",
  "scripts": {
      "start": "node config.js"
  },
  "repository": {
      "type": "git",
      "url": "git+https://github.com/devarashetty/webApplication.git"
  },
  "author": "sairam",
  "license": "ISC",
  "bugs": {
      "url": "https://github.com/devarashetty/webApplication/issues"
  },
  "devDependencies": {
      "babel-core": "^6.0.14",
      "babel-loader": "^6.0.0",
      "webpack": "^1.12.2",
      "webpack-dev-server": "^1.12.1"
  },
  "dependencies": {
      "express": "3.x",
      "http": "*",
      "react": "*",
      "react-dom": "*",
      "react-router": "*",
      "react-router-dom": "*",
      "react-router-config": "*",
      "nodemon": "*",
      "mongodb": "*",
      "semantic-ui-react": "*"
  },
  "homepage": "https://github.com/devarashetty/webApplication#readme"
}

Routes.js

import HomePage from './client/components/home';

我收到错误Unexpected token import。这背后的原因是什么。我认为导入是javascript中可用的默认函数

config.js

var http = require("http");
var mongodb = require("mongodb");
var app = require('express')();
var server = require('http').Server(app);
var routes = require("./routes.js");
var Router = require('react-router');

server.listen(8000);

app.use(function(req, res, next) {
  console.log("------------", req.url);
  var router = Router.create({
      location: req.url,
      routes: routes
  });
  router.run(function(Handler, state) {
      var html = React.renderToString( < Handler / > )
      return res.render('react_page', {
          html: html
     })
  })
});

var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/catering';

MongoClient.connect(url, function(err, db) {
   if (err) {
       console.log('Unable to connect to the mongoDB server. Error:',     err);
   } else {
       console.log('Connection established to', url);

       db.close();
   }
});

1 个答案:

答案 0 :(得分:1)

这是一个有效且可能不是最佳解决方案的解决方案:)

首先在package.json更改start密钥中,如下所示。

"start": "node ./bin/www"

现在创建一个名为bin的文件夹,其中包含一个名为www的文件[注意:它没有任何扩展名]

将以下代码放在www

#!/usr/bin/env node
require("babel-register")({
  presets: ["es2015", "react"],
});
var app = require('../app');
app.set('port', process.env.PORT || 3000);
app.listen(app.get('port'));

第四,将config.js重命名为app.js并在文件末尾添加module.exports = app

确保package.json中包含这些依赖项 [版本可以更新]

"babel-cli": "^6.18.0",
"babel-core": "^6.18.2",
"babel-loader": "^6.2.8",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.11.1",

现在您可以在除上面使用的文件之外的其他文件中使用import