點燈坊

失くすものさえない今が強くなるチャンスよ

11ty Overview

Sam Xiao's Avatar 2021-12-29

11ty is a static site generator with many template engine support. It’s a lightweight tool to embrace JAMstack.

Version

11ty 0.12.1

Create Folder

$ mkdir 11ty-lab

Create a folder for the 11ty project.

overview010

Add Packages

$ yarn init -y
$ yarn add @11ty/eleventy --dev

Use Yarn to add 11ty.

overview000

11ty Config

.eleventy.js

module.exports = () => {
  return {
    htmlTemplateEngine: 'njk',
    dir: {
      input: 'src',
      output: 'dist',
      includes: 'template',
    }
  }
}

Define 11ty setting :

  • htmlTemplateEngine : use Numjucks as the default template engine

  • dir : user-defined directory

    • input : define markdown directory

    • output : define build directory

    • includes : define template directory under input directory

overview001

Template

src/template/index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{{ title }}</title>
</head>
<script>
</script>
<body>
  <header>
    <h1>{{ title }}</h1>
  </header>
  <main>
    {{ content | safe }}
  </main>
</body>
</html>

Define template for Home page.

Line 12

<h1>{{ title }}</h1>

Data binding with title variable.

Line 14

<main>
  {{ content | safe }}
</main>

Data binding with content variable and safe filter to prevent double-escaping in layout.

overview008

Markdown

src/index.md

---
layout: 'index.html'
title: Hello JAMstack
---

### Using 11ty to embrace JAMstack

Markdown with front matter :

  • layout : specify layout for the markdown
  • title : define title variable

overview009

NPM Config

package.json

{
  "name": "11ty-lab",
  "version": "1.0.0",
  "license": "MIT",
  "scripts": {
    "dev": "eleventy --serve",
    "build": "eleventy"
  },
  "devDependencies": {
    "@11ty/eleventy": "^0.12.1"
  }
}

Line 5

"scripts": {
  "dev": "eleventy --serve",
  "build": "eleventy"
},
  • dev : run web server under development mode
  • build : build HTML/CSS/JavaScript under production mode

overview007

Development Mode

$ yarn dev

Start web server under development mode.

overview005

11ty runs successfully under development mode.

overview002

Production Mode

$ yarn build
$ serve dist

Build HTML/CSS/JavaScript under production mode.

overview003

11ty runs successfully under production mode.

overview004

Conclusion

  • Under JAMstack, data is directly from the markdown file, so we need a template engine to transform markdown to HTML by the layout file
  • 11ty support many template engines, and Nunjucks is the most popular one in the 11ty community; even official starter uses Nunjucks
  • We can still use .html as the file extension for Nunjucks, but we have to define htmlTemplateEngine to njk. Since htmlTemplateEngine is default to liquid

Reference

11ty Rocks, Build an 11ty Site in 3 Minutes