gpt4 book ai didi

使用 NextJS 进行 Fastify

转载 作者:行者123 更新时间:2023-12-05 05:03:36 29 4
gpt4 key购买 nike

我正在寻找如何使用 fastify-nextjs 启动 fastify-cli 的建议

我曾尝试将代码简单地添加到建议的位置,但它不起作用。

'use strict'

const path = require('path')
const AutoLoad = require('fastify-autoload')

module.exports = function (fastify, opts, next) {
// Place here your custom code!

fastify.register(require('fastify-nextjs'))
.after(() => {
fastify.next('/hello')
})

// Do not touch the following lines

// This loads all plugins defined in plugins
// those should be support plugins that are reused
// through your application
fastify.register(AutoLoad, {
dir: path.join(__dirname, 'plugins'),
options: Object.assign({}, opts)
})

// This loads all plugins defined in services
// define your routes in one of these
fastify.register(AutoLoad, {
dir: path.join(__dirname, 'services'),
options: Object.assign({}, opts)
})

// Make sure to call next when done
next()

}

最佳答案

我希望这仍然对您有所帮助。

要使用 fastify 客户端注册 nextjs 路由,您首先必须在 plugin 文件夹中的文件中注册 @fastify/nextjs 插件.

环境稳定机制

// plugin/next.js
import fp from "fastify-plugin";
import nextJs from "@fastify/nextjs";

export default fp(async (fastify, opts) => {
fastify.register(nextJs);
});

CommonJs

// plugin/next.js
const fp = require("fastify-plugin");
const nextJs = require("@fastify/nextjs");

module.exports = function fp(async (fastify, opts) {
fastify.register(nextJs);
});

这将使所有路由中的 @fastify/nextjs 插件装饰器可用。 (更多关于 fastify 插件封装在其 documentation 上。)

现在您可以使用 @fastify/nextjs 回复装饰器 nextRender 在 fastify 路由中渲染 nextjs 页面。

例如,如果你有一个 nextjs 页面 pages/index.js,你可以这样渲染它:

环境稳定机制

// plugin/root.js

const root = async (fastify, opts) => {
fastify.get("/", async function (request, reply) {
return reply.nextRender("/");
});

// There is no link between fastify routes and nextjs routes.
// So you can render any nextjs page on any fastity route.
// Here the nextjs page pages/index.js is available also at the
// /app fastify route
fastify.get("/app", async function (request, reply) {
return reply.nextRender("/");
});
};

export default root;

CommonJs

// plugin/root.js

module.exports = async function root(fastify, opts) {
fastify.get("/", async function (request, reply) {
return reply.nextRender("/");
});

// There is no link between fastify routes and nextjs routes.
// So you can render any nextjs page on any fastity route.
// Here the nextjs page pages/index.js is available also at the
// /app fastify route
fastify.get("/app", async function (request, reply) {
return reply.nextRender("/");
});
};

看看这个post如果您打算使用 Typescript 进行编码。

关于使用 NextJS 进行 Fastify,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61543938/

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