Writing Nuxtjs modules

Add to bookmarks

Wed Jun 26 2019

What are nuxt modules

Nuxt modules are extra pieces of code that allow you to extend the core functionality of Nuxtjs in a modularized manner. A few popular modules are Nuxt PWA and Nuxt Auth.

This tutorial assumes you have a basic understanding of the NuxtJs framework

Registering a module

To register a module on your nuxt project, simply append the path to the module in the modules array config option of your project:

modules: [
    ...
    '@nuxtjs/dotenv',
    '~modules/pwa-custom/pwa'
  ],

The first module refers to the @nuxtjs/dotenv module available as a part of your installed npm dependencies. The second line points to a js file (pwa.js in this case) at the path specified relative to the root folder of your project

Convention dictates all modules be stored at the modules folder, though they can theoretically be stored anywhere in your project

All this file would need to do in other to be properly registered as a module would be to export a function.

export default function pwaModule (moduleOptions) {
  // Write your code here
}

In essence, a module is simply a function that is run by NuxtJs.

Config options and context

When the module function is being run by nuxtJs, your function has access to a variety of class functions and configuration options

In the above example: - moduleOptions are passed along with the path to the modules in the configuration files i.e:

modules: [
    ...
    ['~modules/pwa-custom/pwa',{option: value}]
  ],
  • this.options gives you access to all of nuxt's configuration options.
  • this.nuxt is a reference to the nuxt class container, where you can then access things like hooks(to be touched).
  • this is a reference to the module context. This can be used to perform operations like addTemplate() (to be touched).

Getting sh*t done

We'll be going through a list of useful actions and operations that can be done in the module

Hooking on to actions

You can register some parts of your code to run during, before or after certain nuxt actions. You can register a hook in this format:

export default function pwaModule() {
  this.nuxt.hook('action:modifier', parameter => {
    // This will be called when all modules finished loading
  })
}

The most commonly used nuxt hooks are:

  • modules:{before|done} used to hook to module loading related actions.
  • render:{before|done|setupMiddleware|...} used to hook onto render actions
  • build:{before|compile|done...} used to hook to build actions
  • generate:{before|distCopied|...} used to hook on to page generation actions

Adding extra CSS to your site

You can add CSS to the nuxt page by appending to the CSS option of the app:

export default function moduleFunction() {
    this.options.css.push("relative/path/to/css.css");
    //...
}

Register plugins

You can also use the modules addPlugin() method to register plugins in your project. An additional bonus is the plugin file is templated using lodash template. Example plugin registration.

module/name/module.js

this.addPlugin({
    src: path.resolve(__dirname, 'template/plugin.js'),
    options: {
      ua: 123,
      debug: this.options.dev
    }
  })

module/name/templates/plugin.js

// use lodash template
ga('create', '<%= options.ua %>', 'auto')
// gotten from passed options
<% if (options.debug) { %>
// Dev only code
<% } %>

copying files/templates

If you wanted to copy files from your modules folder into the /static folder, for instance, you can use the module container's addTemplate(). The function receives an object as a parameter that contains the following attributes: - src the path to the file that is being copied - options the options are passed to the file which is templated using the lodash template - fileName is the path to the destination file

Sample code:

const path = require('path');

export default function pwaModule() {
  this.nuxt.hook('build:before', () => {
  ...
    this.addTemplate({
    //Copy the service worker from the templates path
      src: path.resolve(__dirname, `./templates/service-worker${ this.options.dev ? '-empty':''}.js`),
      // move it to the static folder
      fileName: path.resolve(this.options.srcDir,`static/service-worker.js`),
    });
  })
}

Generating assets

You can add your content to the generated nuxt assets using a sample code below

export default function forceStyle() {
  const style = '*{outline: yellow !important}'
  this.options.build.plugins.push({
    apply (compiler) {
      compiler.plugin('emit', (compilation, cb) => {
        // This will generate `.nuxt/dist/customstyle.css' variable.
        compilation.assets['customstyle.css'] = { source: () => style, size: () => style.length }
        cb()
      })
    }
  })
}

Conclusion

Nuxt modules give you access to an extra level of modularization and control over your nuxtjs projects. A few things you can learn and try are - Try more module container methods. - Try playing around with hooks.

Fun Fact: This blog is powered by nuxt and the PWA and offline saving of pages are handled by modules

CHEERS!