07.01.2023

How to add a nuxt module from another nuxt module

Recently I wanted to develop a nuxt module that is based on an existing module. But to make the usage as simple as possible, I did not want to just add it as a dependency and require the user to register the dependency module themself. My goal was to provide a seamless experience by just installing my module and only register it; everything regarding the dependency should be handled by the module itself. Like this, the user wouldn't even have to care about the dependency module.

@nuxt/kit to the rescue

The current documentation (as of early january 2023) does not have an example on how to do this, but after digging in the nuxt source code itself, I found a rather simple solution. Honestly, I was really surprised on how simple it is.

During the initialization of nuxt, there is a loop over every registered module, in which every module gets installed (see here):

for (const m of modulesToInstall) {    if (Array.isArray(m)) {        await installModule(m[0], m[1])    } else {        await installModule(m, {})    }}

So I naturally asked myself: where does this mysterious function installModule come from and what does it do?
The answer is easy, if you have a look at the imports in the same file: it is imported from @nuxt/kit. The same package that provides functionality that can be used in modules, too.

So here's what you can do to import another module inside of your module.
First, you need to add the dependency to your modules package.json, so that it gets automatically installed when your module-package is installed.

Second, you install/register the dependency module right in your modules setup-function, just like you would do in your nuxt.config.ts.

// module.tsimport { installModule } from '@nuxt/kit'export interface ModuleOptions {}export default defineNuxtModule<ModuleOptions>({  meta: {    name: 'your-module-name',    configKey: 'yourConfigKey',    compatibility: {      nuxt: '^3.0.0'    }  },  async setup (options, nuxt) {    // automatically install/register the dependency-module    await installModule('dependency-module')  }})

You even can override module options:

await installModule('dependency-module', {    optionA: 'new-option-value'})

Conclusion

I was really surprised when I discovered that it is that simple to install a module from another module using the provided functionality from @nuxt/kit, which even gets used in nuxt itself to install all modules. Great job nuxt team! 🥳