让next.js启动的时候执行一段逻辑
想让next.js启动的时候执行一个函数,今天查了下官网找到了一个解决方案
Instrumentation
文章地址:https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation
If you export a function named register from a instrumentation.ts (or .js) file in the root directory of your project (or inside the src folder if using one), we will call that function whenever a new Next.js server instance is bootstrapped.
在根目录创建一个名为instrumentation.js 的文件,导出一个名为register 的函数,当服务启动的时候会执行这个函数。
文章还说了这个功能是一个实验性的功能,必须在next.config.js中开启这个功能
• This feature is experimental. To use it, you must explicitly opt in by defining experimental.instrumentationHook = true; in your next.config.js.
测试一下
next.config.js
const nextConfig = {
experimental: {
instrumentationHook: true,
},
}
module.exports = nextConfig
instrumentation.js
export async function register() {
console.log("启动完成")
}
测试结果没问题