我正在使用Express开发应用程序,我想在前端运行React。我应该怎么做呢?
我看到人们在他们的布局文件中添加脚本标签(使用CND),其他人使用许多npm包...
最简单的方法是什么?
答案 0 :(得分:1)
使用ES6(使用Babel),买不到你。
<强> server.js 强>
class AutoBoxing {
public static void main(String args[]) {
Integer objInt = 40; // autobox an int
int i = objInt ; // auto-unbox
System.out.println(i + " " + iOb); // displays 40 40
}
}
Html.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"));
});
理论上,您正在设置简单的快速服务器并使用ServerDOM,它响应js服务器端渲染以呈现Html组件。
然后你包括像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;
这样的文件,这个文件可能是使用像webpack之类的东西编译的(只有你想要,我会非常推荐它)然后你只需把它放在Html组件上就可以了完成。