我正在尝试使用 Deno 和 Oak 创建一个简单的 html 页面。
作为视图引擎,我喜欢使用 JSX 生成实际的 html。
这是一个简单的示例,但是失败了,因为 JSX 转换为 React.createElement 并且 React 不可用。
但是我现在需要导入完整的 React 库吗?这可能吗?
(我不需要钩子)
import { Application } from "https://deno.land/x/[email protected]/mod.ts";
import page from "./page.jsx";
const app = new Application();
app.use((ctx) => {
ctx.response.body = page();
});
await app.listen({ port: 8000 });
页面.jsx
export default function() {
return(<div>TEST</div>)
}
我是这样解决的:
deps.ts
export { Application } from "https://deno.land/x/[email protected]/mod.ts";
export { h } from "https://cdn.skypack.dev/preact";
export { render } from "https://cdn.skypack.dev/[email protected]";
home.jsx
/** @jsx h */
import {h} from './deps.ts';
export default function () {
return <div>TEST</div>
}
JSX pragma 是将 React 替换为 h(超脚本)。
您还可以使用 tsconfig.json,如下所示:
{
"compilerOptions": {
"jsxFactory": "h",
}
}
你必须像这样加载它:
deno run --config ./tsconfig.json ...
服务器.js
import { Application, render } from "./deps.ts";
import home from "./home.jsx";
const app = new Application();
const respond = function (ctx, vdom) {
ctx.response.type = "html";
ctx.response.body = render(vdom(), {}, {pretty: true});
};
app.use((ctx) => {
respond(ctx, home);
});
await app.listen({ port: 8000 });
这里是有关在 Deno 中使用 JSX 的更多信息。