fastify-autoload 一个方便的插件动态加载包

发布时间 2023-10-17 09:56:35作者: 荣锋亮

fastify-autoload 是一个方便的fastify 插件加载工具,我们可以基于路径直接加载开发的插件

参考使用

  • 配置
const Fastify = require('fastify')
const path = require("path")
const autoLoad = require('@fastify/autoload');
const app = Fastify({
    logger: true,
    ignoreDuplicateSlashes: true,
}
);
 
app.register(autoLoad, {
    dir: path.join(__dirname, 'plugins')
})
 
app.listen({
    port: 3000,
    host: '0.0.0.0',
    backlog: 511
}, (err, address) => {
    if (err) {
        console.log(err)
        process.exit(1)
    } else {
        console.log(`Server listening on ${address}`)
    }
})
  • 插件开发
    可以是标注的插件,也可以是基于fastify 提供的 fastify-plugin包开发的(这个也是不少官方以及社区插件推荐的开发模式)
    基于fastify-plugin开发的插件
 
const fp = require('fastify-plugin')
function appsPlugin(fastify, opts, next) {
    fastify.get("/app", async (req, res) => {
        let info = {
            ...req.dalong,
            ...fastify.dalongversion,
            id: "dalong app demo"
        }
        console.log(`------${JSON.stringify(info)}----`)
        res.send(info)
    })
    next()
}
// 通过astify-plugin包装插件
module.exports = fp(appsPlugin, {
    name:"app"
})

说明

对于设计开发比较推荐的是可以结合@vercel/ncc, 这样我们打开的应用就比较方便了,在我们的core 部分只提供通用包,每个插件自己开发,然后就是一些标注的commonjs 模块代码(直接基于文件目录加载存储)
打包之后的效果

 

参考资料

https://www.npmjs.com/package/@fastify/autoload
https://github.com/fastify/fastify-autoload
https://github.com/vercel/ncc#readme