【发布时间】: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