简体   繁体   English

SyntaxError: Import React from 'react' Unexpected identifier

[英]SyntaxError: Import React from 'react' Unexpected identifier

I'm trying to run my server.js file locally but every time I try "node server.js" I get a:我正在尝试在本地运行我的 server.js 文件,但每次尝试“node server.js”时,我都会得到:

SyntaxError: Unexpected Identifier for "import React from react SyntaxError: Unexpected Identifier for "import React from react

I'm simply trying to see if I get a console.log("connected") message in a function that accesses my database.我只是想看看我是否在访问我的数据库的 function 中收到 console.log("connected") 消息。

I have already tried adding the "transform-es2015-modules-amd" to my plugins in the package.json file in the Babel section.我已经尝试在 Babel 部分的 package.json 文件中将“transform-es2015-modules-amd”添加到我的插件中。 I have tried almost every other solution offered on Stack Overflow posts similar to mine.我已经尝试了与我类似的 Stack Overflow 帖子上提供的几乎所有其他解决方案。

package.json 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服务器.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 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]

Node does not understand React JSX. Node 不理解 React JSX。 That's what Webpack is for - it uses Babel to transpile your code into vanilla JavaScript.这就是 Webpack 的用途 - 它使用 Babel 将您的代码转换为 vanilla JavaScript。

Looks like you have webpack-dev-server as a dev dependency, so it should already be installed (if you've done an npm install ).看起来你有webpack-dev-server作为开发依赖项,所以它应该已经安装(如果你已经完成了npm install )。 Make sure you have something like this in your package.json scripts field:确保在 package.json scripts字段中有类似的内容:

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

Then run npm run start:dev in your console.然后在控制台中运行npm run start:dev

Shouldn't import react be import React ?不应该import reactimport React吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 import React from 'react' SyntaxError: 意外的标识符 - import React from 'react' SyntaxError: Unexpected identifier 从“react”导入 React 导致 Uncaught SyntaxError: Unexpected identifier - Import React from 'react' results in Uncaught SyntaxError: Unexpected identifier 从“反应”导入反应; 导致 Uncaught SyntaxError: Unexpected identifier - import React from "react"; resulting in Uncaught SyntaxError: Unexpected identifier 无法导入反应,未捕获的语法错误,意外的标识符 - Cannot import react, Uncaught SyntaxError, Unexpected Identifier 未捕获到的SyntaxError:从“反应”导入React中出现意外令牌 - Uncaught SyntaxError: Unexpected token in import React from 'react' 导入语句中的“语法错误:意外的标识符”? - "SyntaxError: Unexpected identifier" from import statement? 尝试使用React制作Chrome扩展程序时出现“未捕获的SyntaxError:意外的标识符” - “Uncaught SyntaxError: Unexpected identifier” when trying to make a Chrome extension with React 文件中的Javascript导入类会产生“未捕获的SyntaxError:意外的标识符” - Javascript import class from file yields “Uncaught SyntaxError: Unexpected Identifier” 导入意外的标识符+ SyntaxError:意外的字符串 - Import Unexpected identifier + SyntaxError: Unexpected string Node.js 看不到模块,意外的标识符从“反应”导入反应 - Node.js don't see module, unexpected identifier import React from 'react'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM