【问题标题】:Resolving JSX syntax error when using CRA (create react app)使用 CRA 时解决 JSX 语法错误(创建反应应用程序)
【发布时间】:2021-04-19 20:58:11
【问题描述】:

我正在尝试在 React 项目上设置服务器端路由。像往常一样,我使用了 CRA。当我尝试从终端运行启动命令时,出现以下屏幕中显示的错误:

谁能帮我解决这个问题?我认为问题在于我正在使用 CRA,因为从我所阅读的内容来看,我似乎需要采取一些额外的步骤才能让我的应用程序在使用 CRA 时读取我的 babel 配置文件。不过我还不太清楚。 这是我的 webpack.config.js 文件的样子:

var path = require('path')
var webpack = require('webpack')
var nodeExternals = require('webpack-node-externals')
var browserConfig = {
  entry: './src/browser/index.js',
  output: {
    path: path.resolve(__dirname, 'public'),
    filename: 'bundle.js',
    publicPath: '/'
  },
  module: {
    rules: [
      { test: /\.(js)$/, use: 'babel-loader' },
    ]
  },
  mode: 'production',
  plugins: [
    new webpack.DefinePlugin({
      __isBrowser__: "true"
    })
  ]
}
var serverConfig = {
  entry: './src/server/index.js',
  target: 'node',
  externals: [nodeExternals()],
  output: {
    path: __dirname,
    filename: 'server.js',
    publicPath: '/'
  },
  mode: 'production',
  module: {
    rules: [
      { test: /\.(js)$/, use: 'babel-loader' }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      __isBrowser__: "false"
    }),
  ]
}
module.exports = [browserConfig, serverConfig]

这是我在服务器目录中的 index.js 文件:

import React from "react";
import express from "express";
import cors from "cors";
import { renderToString } from "react-dom/server";
import App from "../App";
const port = 8000;
const server = express();
server.use(cors());
server.use(express.static("public"));
server.get("*", (req, res, next) => {
  const markup = renderToString(<App />);
  res.send(`
  <!DOCTYPE html>
  <html>
    <head>
        <title>SSR with RR</title>
    </head>
    <body>
        <div id="app">${markup}</div>
    </body>
  </html>
  `);
});
server.listen(port, () => {
  console.log(`Server launched on port ${port}`);
});

【问题讨论】:

    标签: node.js reactjs webpack server-side-rendering


    【解决方案1】:

    您缺少声明@babel/preset-react 预设。在您的 .babelrc 文件中包含其他配置:

    {
      "presets": [
        "@babel/preset-react",
        ...
      ]
    }
    

    确保你有你的 devDependency:

    npm i -D @babel/preset-react
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 2021-07-22
      • 2021-08-16
      • 2022-08-22
      • 2016-08-08
      • 1970-01-01
      • 2020-08-09
      相关资源
      最近更新 更多