Using your Nunjucks design system on 11ty

This guide will help you to use a Nunjucks based design system in your Eleventy website/webapp. You can use Nunjucks both for your components and your documentation.

INFO

Using Eleventy isn't mandatory, you only need your app to use Nunjucks as templating engine for its internal components. However, in the context of SSG, Eleventy is a nice candidate to run pages powered by Nunjucks.

To make reusable components, we declare them as macro, like:

{% macro btn(label) %}
  <button>{{ label }}</button>
{% endmacro %}

Installation and usage

Pre-requisites (in your local environment)

  1. Create a new Eleventy app

    $ mkdir my-11ty-app
    $ cd my-11ty-app
    $ npm init -y
    
  2. Add the dependencies we'll need to run the project, like 11ty, and Sass for styling:

    $ npm install @11ty/eleventy sass npm-run-all --save-dev
    
  3. Add npm scripts to run your development tasks in your package.json file:

    "scripts": {
      "watch:11ty": "eleventy --serve",
      "watch:sass": "sass --no-source-map --watch sass:_site/css",
      "watch": "npm-run-all build:sass --parallel watch:*",
      "build:sass": "sass --no-source-map sass:_site/css",
      "start": "npm-run-all watch"
    }
    

Add your design system from Backlight

Follow the standard procedure to install your Design System in your local project.

Use your design system in your local project

INFO

In the following instructions, keep in mind to use the right path to your design system as set in the npm registry (e.g. @backlight-dev/john.design-system) . Have a look at the node_modules folder.

  1. Edit the package.json Sass script to set import paths to the design system root:

    "watch:sass": "sass --load-path=node_modules/@backlight-dev/john.design-system --no-source-map --watch sass:_site/css",
    "build:sass": "sass --load-path=node_modules/@backlight-dev/john.design-system --no-source-map sass:_site/css",
    
  2. Add an .eleventy.js config file at the root level of your folder to set the design system root in the Nunjucks' loading paths:

    let Nunjucks = require('nunjucks');
    
    module.exports = function (eleventyConfig) {
      let nunjucksEnvironment = new Nunjucks.Environment(
        new Nunjucks.FileSystemLoader([
          'node_modules/@backlight-dev/john.design-system/',
        ])
      );
      eleventyConfig.setLibrary('njk', nunjucksEnvironment);
    };
    
  3. Create a sass/main.scss file to import your design system globals and components' styles:

    @import 'theme/src/theme.scss';
    @import 'button/src/_button.scss';
    
  4. In your default layout, add a reference to this main.scss file:

    <link rel="stylesheet" href="/css/main.css" />
    
  5. In your layouts, import your components as any other Nunjucks regular files:

    {% import "button/src/button.njk" as Button %}
    {{ Button.btn("Hello Rioters 🤘 !") }}
    

Resources

*[SSG]: Static Site Generation