gpt4 book ai didi

express - 如何将 React 添加到 Express 应用程序?

转载 作者:行者123 更新时间:2023-12-03 14:28:52 24 4
gpt4 key购买 nike

我正在使用 Express 开发一个应用程序,我想在前端运行 React。我该怎么办?

我见过人们将脚本标签(使用 CND)添加到他们的布局文件中,其他人使用许多 npm 包......

最简单的方法是什么?

最佳答案

使用ES6(带有 Babel ),不必购买。

server.js

import "babel-core/polyfill";
import path from "path";
import express from "express";
import React, { DOM } from "react";
import ServerDOM from "react-dom/server";
import Html from "./components/Html";

const server = express();

server.set("port", (process.env.PORT || config.port));
server.use(express.static(path.join(__dirname, "public")));
server.use("/", (req, res, next) =>
{
const html = ServerDOM.renderToStaticMarkup(React.createElement(Html));
res.status(200).send("<!doctype html>" + html);
});

server.get("*", async (req, res, next) =>
{
try
{
let statusCode = 200;
const html = ServerDOM.renderToStaticMarkup(React.createElement(Html));

res.status(statusCode).send("<!doctype html>" + html);
}
catch (e) { next(e) }
});

server.listen(server.get("port"), () =>
{
console.log("\nServer running at localhost:%d\n", server.get("port"));
});

Html.js (组件)

import React, { Component, PropTypes, DOM, createElement as $ } from "react";

class Html extends Component
{
static propTypes =
{
title: PropTypes.string,
description: PropTypes.string
};

static defaultProps =
{
title: "",
description: ""
};

render()
{
const { title, description, children } = this.props;

return (
DOM.html({},
DOM.head({},
DOM.meta({charSet: "utf-8"}),
DOM.meta({httpEquiv: "X-UA-Compatible", content: "IE=edge"}),
DOM.meta({name: "description", content: description}),
DOM.meta({name: "viewport", content: "width=device-width, initial-scale=1"}),
DOM.link({rel: "stylesheet", href: "/app.css", type: "text/css"}),
DOM.title({}, title)
),
DOM.body({},
DOM.div({id: "app"}, children),
DOM.script({src: "/app.js"})
)
)
)
}
}

export default Html;

理论上,您正在设置简单的express服务器并使用ServerDOM(React js服务器端渲染)来渲染Html组件。然后你包括像 app.js 这样的文件,它可能是使用类似 webpack 编译的包。 (只要你愿意,我会极力推荐它)然后你只需将它放在 Html 组件上就可以了。

关于express - 如何将 React 添加到 Express 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37795954/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com