Exploring Nuxt Modules

Discover our list of modules to supercharge your Nuxt project, created by the Nuxt team and community.

  • 165+ Modules
  • 105+ Maintainers

modules - 图1

Check out modules.nuxtjs.org

modules-in-nuxt-js

While developing production-grade applications with Nuxt.js you might find that the framework’s core functionality is not enough. Nuxt.js 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.js very complex and hard to use.

This is one of the reasons why Nuxt.js provides a higher-order module system that makes it possible to extend the core. Modules are functions that are called sequentially when booting Nuxt.js. The framework waits for each module to finish before continuing. In this way, modules can customize almost any aspect of your project. Thanks to Nuxt.js’ 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.js modules can be incorporated into npm packages. This makes it possible to reuse across projects and to share with the community, helping create an ecosystem of high-quality add-ons.

The modules Property

Modules are Nuxt.js extensions which can extend the framework’s core functionality and add endless integrations. Once you have installed the modules you can then add them to your nuxt.config.js file under the modules property.

nuxt.config.js

  1. export default {
  2. modules: [
  3. // Using package name
  4. '@nuxtjs/axios',
  5. // Relative to your project srcDir
  6. '~/modules/awesome.js',
  7. // Providing options
  8. ['@nuxtjs/google-analytics', { ua: 'X1234567' }],
  9. // Inline definition
  10. function () {}
  11. ]
  12. }

modules - 图3

Module developers usually provide additionally needed steps and details for usage.

Nuxt.js tries to resolve each item in the modules array using node require path (in the node_modules) and then will resolve from the project srcDir if @ alias is used.

modules - 图4

Modules are executed sequentially so the order is important.

Modules should export a function to enhance build/runtime and optionally return a promise until their job is finished. Note that they are imported at runtime so they should be already transpiled if using modern ES6 features.

Write your own Module

Modules are functions. They can be packaged as npm modules or directly included in your project source code.

nuxt.config.js

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

modules/example.js

  1. export default function ExampleModule(moduleOptions) {
  2. console.log(moduleOptions.token) // '123'
  3. console.log(this.options.exampleMsg) // 'hello'
  4. this.nuxt.hook('ready', async nuxt => {
  5. console.log('Nuxt is ready')
  6. })
  7. }
  8. // REQUIRED if publishing the module as npm package
  9. module.exports.meta = require('./package.json')

1) ModuleOptions

moduleOptions: This is the object passed using the modules array by the user. We can use it to customize its behavior.

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: [['@nuxtjs/axios', { anotherOption: true }]],
  3. // axios module is aware of this by using `this.options.axios`
  4. axios: {
  5. option1,
  6. option2
  7. }
  8. }

2) this.options

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

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. }

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'] = {
  9. source: () => info,
  10. size: () => info.length
  11. }
  12. cb()
  13. })
  14. }
  15. })
  16. }

3) this.nuxt

this.nuxt: This is a reference to the current Nuxt.js instance. We can register hooks on certain life cycle events.

  • Ready : Nuxt is ready to work (ModuleContainer and Renderer ready).
  1. nuxt.hook('ready', async nuxt => {
  2. // Your custom code here
  3. })
  • Error: An unhandled error when calling hooks.
  1. nuxt.hook('error', async error => {
  2. // Your custom code here
  3. })
  • Close: Nuxt instance is gracefully closing.
  1. nuxt.hook('close', async nuxt => {
  2. // Your custom code here
  3. })
  • Listen: Nuxt internal server starts listening. (Using nuxt start or nuxt dev)
  1. nuxt.hook('listen', async (server, { host, port }) => {
  2. // Your custom code here
  3. })

this: Context of modules. All modules will be called within context of the ModuleContainer instance.

Please look into the ModuleContainer class docs for available methods.

Run Tasks on Specific hooks

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

Here are some basic examples:

modules/myModule.js

  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. }

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. }

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/blob/dev/packages/webpack/src/config/base.js
  11. const barLoader = config.module.rules.find(rule => rule.loader === 'bar-loader')
  12. })
  13. }

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 asynchronous Operation. For this, Nuxt.js supports async modules which can return a Promise or call a callback.

Use async/await

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

Return a Promise

  1. export default function asyncModule($http) {
  2. return $http
  3. .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. }

modules - 图5

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

Publishing your module

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

modules/myModule.js

  1. module.exports.meta = require('./package.json')

buildModules

Some modules are only imported during development and build time. Using buildModules helps to make production startup faster and also significantly decrease the size of your node_modules for production deployments. Please refer to the docs for each module to see if it is recommended to use modules or buildModules.

The usage difference is:

  • Instead of adding to modules inside nuxt.config.js, use buildModules

nuxt.config.js

  1. export default {
  2. buildModules: ['@nuxtjs/eslint-module']
  3. }
  • Instead of adding to dependencies inside package.json, use devDependencies
  1. yarn add -D @nuxtjs/eslint-module
  1. npm install --save-dev @nuxtjs/eslint-module

modules - 图6

If you are a module author, It is highly recommended to suggest to users to install 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)

modules - 图7

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.