让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("启动完成")
}
测试结果没问题
![image](https://prod-files-secure.s3.us-west-2.amazonaws.com/371abca5-94fd-4d13-a43e-bbcb27be7c63/6d77d197-bfac-47af-8703-573bd3bebd95/Untitled.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=AKIAT73L2G45HZZMZUHI%2F20240727%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20240727T112226Z&X-Amz-Expires=3600&X-Amz-Signature=0440c381d9ccfc00132b281ea78a1463eb085b60596f54f31409e40870e3189a&X-Amz-SignedHeaders=host&x-id=GetObject)