Introduction to Metalsmith
Metalsmith is a versatile and powerful static site generator engine written in Node.js. It allows you to transform a directory of source files into a completely different structured set of files, making it perfect for generating static websites, blogs, or even documentation.
Getting Started with Metalsmith
First, install Metalsmith using npm:
npm install metalsmith --save
Then create a simple build script:
const Metalsmith = require('metalsmith'); Metalsmith(__dirname) .source('./src') .destination('./build') .build((err) => { if (err) throw err; });
Useful Metalsmith APIs
1. Using Plugins
Metalsmith’s true power lies in its use of plugins. Here’s an example of how to use the metalsmith-markdown
plugin:
const markdown = require('@metalsmith/markdown'); Metalsmith(__dirname) .source('./src') .destination('./build') .use(markdown()) .build((err) => { if (err) throw err; });
2. Collections API
Organize your content into collections:
const collections = require('metalsmith-collections'); Metalsmith(__dirname) .source('./src') .destination('./build') .use(collections({ articles: '*.md', })) .build((err) => { if (err) throw err; });
3. Permalinks API
Define clean URLs for your posts:
const permalinks = require('@metalsmith/permalinks'); Metalsmith(__dirname) .source('./src') .destination('./build') .use(permalinks({ relative: false, })) .build((err) => { if (err) throw err; });
4. Layouts API
Apply layouts to your content:
const layouts = require('@metalsmith/layouts'); Metalsmith(__dirname) .source('./src') .destination('./build') .use(layouts({ engine: 'handlebars', directory: 'layouts', })) .build((err) => { if (err) throw err; });
Example Application
Combining the APIs, here’s an example application:
const Metalsmith = require('metalsmith'); const markdown = require('@metalsmith/markdown'); const collections = require('metalsmith-collections'); const permalinks = require('@metalsmith/permalinks'); const layouts = require('@metalsmith/layouts'); Metalsmith(__dirname) .source('./src') .destination('./build') .use(markdown()) .use(collections({ articles: '*.md', })) .use(permalinks({ relative: false, })) .use(layouts({ engine: 'handlebars', directory: 'layouts', })) .build((err) => { if (err) throw err; });
This example reads Markdown files from the src
directory, converts them to HTML, organizes them into collections, transforms their URLs, and applies Handlebars layouts before writing the final site to the build
directory.
Hash: 5631d28de398da1298164a3f23e6a4b884e57060c11fee41f8f52ee8e5100a43