语法错误:从“反应”意外标识符导入React

时间:2019-11-08 21:48:40

标签: javascript node.js reactjs

我试图在本地运行server.js文件,但是每次尝试“ node server.js”时,我都会得到:

  

SyntaxError:“从react导入React的意外标识符

我只是想查看是否在访问数据库的函数中收到console.log(“ connected”)消息。

我已经尝试在Babel部分的package.json文件中的插件中添加“ transform-es2015-modules-amd”。我已经尝试了与我类似的Stack Overflow帖子上提供的几乎所有其他解决方案。

package.json

{
  "dependencies": {
    "atob": "^2.1.2",
    "axios": "^0.19.0",
    "babel-loader": "^8.0.0-beta.6",
    "babel-upgrade": "^1.0.1",
    "btoa": "^1.2.1",
    "concurrently": "^5.0.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql": "^2.17.1",
    "node-fetch": "^2.6.0",
    "react": "^16.11.0",
    "react-dom": "^16.11.0",
    "react-redux": "^7.1.1",
    "react-router": "^5.1.2",
    "react-router-dom": "^5.1.2",
    "redux": "^4.0.4",
    "request": "^2.88.0",
    "serialize-javascript": "^2.1.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.6.4",
    "@babel/core": "^7.6.4",
    "@babel/node": "^7.6.3",
    "@babel/preset-env": "^7.6.3",
    "@babel/preset-react": "^7.6.3",
    "@types/node": "^12.11.2",
    "babel-loader": "^8.0.6",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^3.2.0",
    "nodemon": "^1.19.4",
    "style-loader": "^1.0.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.9",
    "webpack-dev-server": "^3.9.0",
    "webpack-node-externals": "^1.7.2"
  },
  "babel": {
    "presets": [
      "@babel/preset-react",
      "@babel/preset-env"
    ]
  "plugins": [
      "transform-es2015-modules-amd"
    ]
  }
}                                                                                                                                                                                   

server.js

import React from 'react';
import { StaticRouter } from 'react-router-dom';
import { Provider as ReduxProvider } from "react-redux";

import App from '../client/src/App.js';
import { renderToString } from "react-dom/server";
import createStore, { initialize, fetchCharacters } from './store.js';

var path = require("path");
var express = require("express");
var serialize = require("serialize-javascript");
var db = require('./db');

const PORT = process.env.HTTP_PORT || 4001;
const app = express();
app.use('/static', express.static(path.join(__dirname, 'public')));
console.log(__dirname);

app.get('/*', function(req, res) {
  const context = {};
  const store = createStore();
  store.dispatch(initialize());

  Promise.all([store.dispatch(fetchCharacters())]).then(() => {
    const component = (
      <ReduxProvider store={store}>
        <StaticRouter location={req.url} context={context}>
          <App/>
        </StaticRouter>
      </ReduxProvider>
    );
    const ss_react = renderToString(component);
    const ss_state = store.getState();

    res.writeHead( 200, { "Content-Type": "text/html" });
    res.end(htmlTemplate(component, ss_state));
  });
});

function htmlTemplate(component, ss_state) {
    return `
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>React SSR</title>
        </head>

   `;
}

app.listen(PORT, () => {
    console.log(`server listening at port ${PORT}. `);
});

webpack.config.js

const webpack = require('webpack')
const nodeExternals = require('webpack-node-externals')
const path = require('path')

const js = {
  test: /\.m?(js|jsx)$/,
  exclude: /(node_modules|bower_components)/,
  use: {
    loader: 'babel-loader'
  }
}

const css = {
    test: /\.css$/,
    use: [
      "style-loader",
      {
        loader: "css-loader",
        options: {
          modules: true
        }
      }
    ]
}

const serverConfig = {
  mode: 'development',
  target: 'node',
  node: {
    __dirname: false
  },
  externals: [nodeExternals()],
  entry: {
    'index.js': path.resolve(__dirname, 'server/server.js')
  },
  module: {
    rules: [js]
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name]'
  }
}

const clientConfig = {
  mode: 'development',
  target: 'web',
  entry: {
    'index.js': path.resolve(__dirname, 'client/src/index.js')
  },
  module: {
    rules: [js, css]
  },
  optimization: {
    splitChunks: {
      chunks: 'all'
    }
  },
  output: {
    path: path.resolve(__dirname, 'dist/public'),
    filename: '[name]'
  }
}

module.exports = [serverConfig, clientConfig]

1 个答案:

答案 0 :(得分:1)

Node不了解React JSX。这就是Webpack的目的-它使用Babel将您的代码转换为原始JavaScript。

好像您将webpack-dev-server作为开发依赖项,因此应该已经安装了它(如果您已完成npm install)。确保您的package.json scripts字段中包含以下内容:

"scripts": {
  "start:dev": "webpack-dev-server --config webpack.config.js"
},

然后在您的控制台中运行npm run start:dev