Modules

Modules are Nuxt.js extensions which can extend its core functionality and add endless integrations.

Introduction

While developing production-grade applications with Nuxt, you'll soon discover that the framework's corefunctionality is not enough. Nuxt can be extended with configuration options and plugins,but maintaining these customizations across multiple projects is tedious, repetitive and time-consuming.On the other hand, supporting every project's needs out of the box would make Nuxt very complex and hard to use.

This is one of the reasons why Nuxt provides a higher-order module system that makes it easy to extend the core.Modules are simply functions that are called sequentially when booting Nuxt.The framework waits for each module to finish before continuing.In this way, modules can customize almost any aspect of Nuxt.Thanks to Nuxt's modular design (based on webpack's Tapable),modules can easily register hooks for certain entry points like the builder initialization.Modules can also override templates, configure webpack loaders, add CSS libraries, and perform many other useful tasks.

Best of all, Nuxt modules can be incorporated into npm packages.This makes them easy to reuse across projects and to share with the Nuxt community,helping create an ecosystem of high-quality Nuxt add-ons.

Modules are great if you:

  • Are a member of an agile team that needs to quickly bootstrap new projects.
  • Are tired of re-inventing the wheel for common tasks like integrating Google Analytics.
  • Are a lovely Open Source enthusiast who would like to easily share your work with the community.
  • Are a member of an enterprise company that values quality and reusability.
  • Are often up against short deadlines and don't have time to dig into the details of every new library or integration.
  • Are tired of dealing with breaking changes to low-level interfaces, and need things that just work™.

List of Nuxt.js modules

The Nuxt.js team offers official modules:

  • @nuxt/http: Light and universal way to make HTTP requests, based on ky-universal
  • @nuxtjs/axios: Secure and Easy Axios integration with Nuxt.js to make HTTP requests
  • @nuxtjs/pwa: Supercharge Nuxt with a heavily tested, updated and stable PWA solution
  • @nuxtjs/auth: Authentication module for Nuxt.js, offering different schemes and strategies

A list of Nuxt.js modules made by the community is available on https://github.com/topics/nuxt-module

Write a basic Module

As already mentioned modules are just simple functions. They can be packaged as npm modules or directly included in project source code.

modules/simple.js

  1. export default function SimpleModule (moduleOptions) {
  2. // Write your code here
  3. }
  4. // REQUIRED if publishing the module as npm package
  5. // module.exports.meta = require('./package.json')

moduleOptions

This is the object passed using modules array by user we can use it to customize it's behavior.

this.options

You can directly access Nuxt options using this reference. This is the content of the user's nuxt.config.js with all default options assigned to. It can be used for shared options between modules.

this.nuxt

This is a reference to current Nuxt instance. Refer to Nuxt class docs for available methods.

this

Context of modules. Please look into the ModuleContainer class docs for available methods.

module.exports.meta

This line is required if you are publishing module as an npm package. Nuxt internally uses meta to work better with your package.

nuxt.config.js

  1. export default {
  2. modules: [
  3. // Simple usage
  4. '~/modules/simple'
  5. // Passing options directly
  6. ['~/modules/simple', { token: '123' }]
  7. ]
  8. }

We then tell Nuxt to load some specific modules for a project with optional parameters as options.Please refer to modules configuration docs for more info!

Async Modules

Not all modules will do everything synchronous. For example you may want to develop a module which needs fetching some API or doing async IO. For this, Nuxt supports async modules which can return a Promise or call a callback.

Build-only Modules

Usually, modules are only required during development and build time. Using buildModules helps to make production startup faster and also significantly decreasing node_modules size for production deployments. If you are a module author, It is highly recommended to suggest users installing your package as a devDependency and use buildModules instead of modules for nuxt.config.js.

Your module is a buildModule unless:

  • It is providing a serverMiddleware
  • It has to register a Node.js runtime hook (Like sentry)
  • It is affecting vue-renderer behavior or using a hook from server: or vue-renderer: namespace
  • Anything else that is outside of webpack scope (Hint: plugins and templates are compiled and are in webpack scope)

NOTE: If you are going to offer using buildModules please mention that this feature is only available since Nuxt v2.9. Older users should upgrade Nuxt or use the modules section.

Use async/await

  1. import fse from 'fs-extra'
  2. export default async function asyncModule () {
  3. // You can do async works here using `async`/`await`
  4. const pages = await fse.readJson('./pages.json')
  5. }

Return a Promise

  1. import axios from 'axios'
  2. export default function asyncModule () {
  3. return axios.get('https://jsonplaceholder.typicode.com/users')
  4. .then(res => res.data.map(user => '/users/' + user.username))
  5. .then((routes) => {
  6. // Do something by extending Nuxt routes
  7. })
  8. }

Common Snippets

Top level options

Sometimes it is more convenient if we can use top level options while registering modules in nuxt.config.js.This allows us to combine multiple option sources.

nuxt.config.js

  1. export default {
  2. modules: [
  3. ['@nuxtjs/axios', { anotherOption: true }]
  4. ],
  5. // axios module is aware of this by using `this.options.axios`
  6. axios: {
  7. option1,
  8. option2
  9. }
  10. }

module.js

  1. export default function (moduleOptions) {
  2. // `options` will contain option1, option2 and anotherOption
  3. const options = Object.assign({}, this.options.axios, moduleOptions)
  4. // ...
  5. }

Provide plugins

It is common that modules provide one or more plugins when added.For example bootstrap-vue module would require to register itself into Vue.In such situations we can use the this.addPlugin helper.

plugin.js

  1. import Vue from 'vue'
  2. import BootstrapVue from 'bootstrap-vue/dist/bootstrap-vue.esm'
  3. Vue.use(BootstrapVue)

module.js

  1. import path from 'path'
  2. export default function nuxtBootstrapVue (moduleOptions) {
  3. // Register `plugin.js` template
  4. this.addPlugin(path.resolve(__dirname, 'plugin.js'))
  5. }

Template plugins

Registered templates and plugins can leverage lodash templates to conditionally change registered plugins output.

plugin.js

  1. // Set Google Analytics UA
  2. ga('create', '<%= options.ua %>', 'auto')
  3. <% if (options.debug) { %>
  4. // Dev only code
  5. <% } %>

module.js

  1. import path from 'path'
  2. export default function nuxtBootstrapVue (moduleOptions) {
  3. // Register `plugin.js` template
  4. this.addPlugin({
  5. src: path.resolve(__dirname, 'plugin.js'),
  6. options: {
  7. // Nuxt will replace `options.ua` with `123` when copying plugin to project
  8. ua: 123,
  9. // conditional parts with dev will be stripped from plugin code on production builds
  10. debug: this.options.dev
  11. }
  12. })
  13. }

Add a CSS library

If your module will provide a CSS library, make sure to perform a check if the user already included the library to avoid duplicates, and add an option to disable the CSS library in the module.

module.js

  1. export default function (moduleOptions) {
  2. if (moduleOptions.fontAwesome !== false) {
  3. // Add Font Awesome
  4. this.options.css.push('font-awesome/css/font-awesome.css')
  5. }
  6. }

Emit assets

We can register webpack plugins to emit assets during build.

module.js

  1. export default function (moduleOptions) {
  2. const info = 'Built by awesome module - 1.3 alpha on ' + Date.now()
  3. this.options.build.plugins.push({
  4. apply (compiler) {
  5. compiler.plugin('emit', (compilation, cb) => {
  6. // This will generate `.nuxt/dist/info.txt' with contents of info variable.
  7. // Source can be buffer too
  8. compilation.assets['info.txt'] = { source: () => info, size: () => info.length }
  9. cb()
  10. })
  11. }
  12. })
  13. }

Register custom webpack loaders

We can do the same as build.extend in nuxt.config.js using this.extendBuild.

module.js

  1. export default function (moduleOptions) {
  2. this.extendBuild((config, { isClient, isServer }) => {
  3. // `.foo` Loader
  4. config.module.rules.push({
  5. test: /\.foo$/,
  6. use: [...]
  7. })
  8. // Customize existing loaders
  9. // Refer to source code for Nuxt internals:
  10. // https://github.com/nuxt/nuxt.js/tree/dev/packages/builder/src/webpack/base.js
  11. const barLoader = config.module.rules.find(rule => rule.loader === 'bar-loader')
  12. })
  13. }

Run Tasks on Specific hooks

Your module may need to do things only on specific conditions and not just during Nuxt initialization.We can use the powerful Hookable Nuxt.js system to do tasks on specific events.Nuxt will wait for your function if it return a Promise or is defined as async.

Here are some basic examples:

  1. export default function myModule () {
  2. this.nuxt.hook('modules:done', (moduleContainer) => {
  3. // This will be called when all modules finished loading
  4. })
  5. this.nuxt.hook('render:before', (renderer) => {
  6. // Called after the renderer was created
  7. })
  8. this.nuxt.hook('build:compile', async ({ name, compiler }) => {
  9. // Called before the compiler (default: webpack) starts
  10. })
  11. this.nuxt.hook('generate:before', async (generator) => {
  12. // This will be called before Nuxt generates your pages
  13. })
  14. }

Module package commands

Experimental

Starting in v2.4.0, you can add custom nuxt commands through a Nuxt module's package. To do so, you must follow the NuxtCommand API when defining your command. A simple example hypothetically placed in my-module/bin/command.js looks like this:

  1. #!/usr/bin/env node
  2. const consola = require('consola')
  3. const { NuxtCommand } = require('@nuxt/cli')
  4. NuxtCommand.run({
  5. name: 'command',
  6. description: 'My Module Command',
  7. usage: 'command <foobar>',
  8. options: {
  9. foobar: {
  10. alias: 'fb',
  11. type: 'string',
  12. description: 'Simple test string'
  13. }
  14. },
  15. run (cmd) {
  16. consola.info(cmd.argv)
  17. }
  18. })

A few things of note here. First, notice the call to /usr/bin/env to retrieve the Node executable. Also notice that ES module syntax can't be used for commands unless you manually incorporate esm into your code.

Next, you'll notice how NuxtCommand.run() is used to specify the settings and behavior of the command. Options are defined in options, which get parsed via minimist.Once arguments are parsed, run() is automatically called with the NuxtCommand instance as first parameter.

In the example above, cmd.argv is used to retrieve parsed command-line arguments. There are more methods and properties in NuxtCommand — documentation on them will be provided as this feature is further tested and improved.

To make your command recognizable by the Nuxt CLI, list it under the bin section of your package.json, using the nuxt-module convention, where module relates to your package's name. With this central binary, you can use argv to further parse more subcommands for your command if you desire.

  1. {
  2. "bin": {
  3. "nuxt-foobar": "./bin/command.js"
  4. }
  5. }

Once your package is installed (via NPM or Yarn), you'll be able to execute nuxt foobar … on the command-line.

There are way more hooks and possibilities for modules. Please read the Nuxt Internals to find out more about the nuxt-internal API.