For this week, I have been reading unbuild source code and found few packages that I have never seen before or used. I wanted to share some interesting packages that are used in these OSS projects so we can learn a thing or two ;)
The following are discussed in this article:
What is hookable?
Hookable’s usage in unbuild
What is hookable?
Hookable is a package built by authors at Unjs. Unjs provides JS tools, libraries and has about 63 npm packages and 421m downloads per month. Sheesh, that’s a lot.
Hookable repository has this description “Awaitable Hooks”.
This package is straightforward to use:
Install
npm install hookable
Usage
// Method A:
import { createHooks } from 'hookable'
// Create a hookable instance
const hooks = createHooks()
// Hook on 'hello'
hooks.hook('hello', () => { console.log('Hello World' )})
// Call 'hello' hook
hooks.callHook('hello')
Basically, you create a hook with a callback and call these hooks somewhere else in your codebase to trigger this callback. Let’s what sort of hooks are found in unbuild source code.
Hookable’s usage in unbuild
Initializing hookable
At line 182 in build.ts, you will find the below code:
// Build context
const ctx: BuildContext = {
options,
jiti,
warnings: new Set(),
pkg,
buildEntries: [],
usedImports: new Set(),
hooks: createHooks(),
};
Register hooks
At the line 185 in build.ts, you will find the below code:
// Register hooks
if (preset.hooks) {
ctx.hooks.addHooks(preset.hooks);
}
if (inputConfig.hooks) {
ctx.hooks.addHooks(inputConfig.hooks);
}
if (buildConfig.hooks) {
ctx.hooks.addHooks(buildConfig.hooks);
}
Calling the hooks
In build.ts, you will find the below code used to call registered hooks:
// Allow prepare and extending context
await ctx.hooks.callHook("build:prepare", ctx);
// Call build:before
await ctx.hooks.callHook("build:before", ctx);
// Skip rest for stub and watch mode
if (options.stub || options.watch) {
await ctx.hooks.callHook("build:done", ctx);
return;
}
// Call build:done
await ctx.hooks.callHook("build:done", ctx);
About me:
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.
I am open to work on interesting projects. Send me an email at ramu.narasinga@gmail.com
My Github — https://github.com/ramu-narasinga
My website — https://ramunarasinga.com
My Youtube channel — https://www.youtube.com/@thinkthroo
Learning platform — https://thinkthroo.com
Codebase Architecture — https://app.thinkthroo.com/architecture
Best practices — https://app.thinkthroo.com/best-practices
Production-grade projects — https://app.thinkthroo.com/production-grade-projects
Top comments (0)