创建适配器
创建一个实现 NextAdapter 接口的适配器模块。
适配器是一个导出实现了 NextAdapter 接口的对象的模块。
该接口可以从 next 包中导入:
typescript
import type { NextAdapter } from 'next'该接口定义如下:
typescript
type Route = {
source?: string
sourceRegex: string
destination?: string
headers?: Record<string, string>
has?: RouteHas[]
missing?: RouteHas[]
status?: number
priority?: boolean
}
export interface AdapterOutputs {
pages: Array<AdapterOutput['PAGES']>
middleware?: AdapterOutput['MIDDLEWARE']
appPages: Array<AdapterOutput['APP_PAGE']>
pagesApi: Array<AdapterOutput['PAGES_API']>
appRoutes: Array<AdapterOutput['APP_ROUTE']>
prerenders: Array<AdapterOutput['PRERENDER']>
staticFiles: Array<AdapterOutput['STATIC_FILE']>
}
export interface NextAdapter {
name: string
modifyConfig?: (
config: NextConfigComplete,
ctx: {
phase: PHASE_TYPE
nextVersion: string
projectDir: string
}
) => Promise<NextConfigComplete> | NextConfigComplete
onBuildComplete?: (ctx: {
routing: {
beforeMiddleware: Array<Route>
middlewareMatchers: Array<Route>
beforeFiles: Array<Route>
afterFiles: Array<Route>
dynamicRoutes: Array<Route>
onMatch: Array<Route>
fallback: Array<Route>
shouldNormalizeNextData: boolean
rsc: RoutesManifest['rsc']
}
outputs: AdapterOutputs
projectDir: string
repoRoot: string
distDir: string
config: NextConfigComplete
nextVersion: string
buildId: string
}) => Promise<void> | void
}基本适配器结构#
以下是一个最小化的适配器示例:
my-adapter.js
/** @type {import('next').NextAdapter} */
const adapter = {
name: 'my-custom-adapter',
async modifyConfig(config, { phase }) {
// 根据构建阶段修改 Next.js 配置
if (phase === 'phase-production-build') {
return {
...config,
// 添加你的修改
}
}
return config
},
async onBuildComplete({
routing,
outputs,
projectDir,
repoRoot,
distDir,
config,
nextVersion,
buildId,
}) {
// 处理构建输出
console.log('Build completed with', outputs.pages.length, 'pages')
console.log('Build ID:', buildId)
console.log('Dynamic routes:', routing.dynamicRoutes.length)
// 访问生成的输出条目
for (const page of outputs.pages) {
console.log('Page:', page.pathname, 'at', page.filePath)
}
for (const apiRoute of outputs.pagesApi) {
console.log('API Route:', apiRoute.pathname, 'at', apiRoute.filePath)
}
for (const appPage of outputs.appPages) {
console.log('App Page:', appPage.pathname, 'at', appPage.filePath)
}
for (const prerender of outputs.prerenders) {
console.log('Prerendered:', prerender.pathname)
}
},
}
module.exports = adapter