a blog for those who code

Monday 6 February 2017

Create a Static Site with Metalsmith

In this post we will be discussing about creating a static site with Metalsmith. Metalsmith is an extremely simple,lightweight and pluggable static site generator, which supports a wide range of template and data format options. It uses a modular structure and has a very few dependencies.


Static site are websites that is delivered to the user exactly as it is stored, thus displays the same information for all users. Metalsmith is a static site generator which creates static build files that can be deployed to a web server. The good thing about Metalsmith is that all the logic in Metalsmith is handled by plugins which can be chained together.

Install Metalsmith

Make sure you have installed npm and Node.js. After installing you can install metalsmith by using the command

npm install --save-dev metalsmith

We also have to install metalsmith-markdown (which is a Metalsmith plugin to convert markdown plugins) and metalsmith-layouts (which use the given templating engine)

npm install --save-dev metalsmith-markdown
npm install --save-dev metalsmith-layouts

At first we will create a folder called src and create an .md (markdown) file to pass the data. Having your content in Markdown is very common where we will use the existing plugin which will process markdown and convert it to html. The content of the .md file is :

---
title: Hello CodingDefined.com
layout: layout.html
---
Welcome to Static Site 

Which will be converted to the following JavaScript object :

{
  title : Hello CodingDefined.com,
  layout : layout.html,
  contents : new Buffer('Welcome to Static Site ')
}

Next thing is to create a layout.html file in the layouts directory as shown below :

<!doctype html>
<html>
<head>
  <title>{{title}}</title>
</head>
<body>
  {{contents}}
</body>
</html>

To build our site, we need to define an output folder and run a script or you can simply say a build file. Create the build file index.js as shown below :

var metalsmith = require('metalsmith');
var markdown = require('metalsmith-markdown');

metalsmith(__dirname)
    .source('src')
    .destination('dist')
    .use(markdown())
    .build(function(err) {
      if(err) {
console.log(err);
      }
    });

Now after this just run a command node index.js which will create an html file in the dist folder as shown below :


Metalsmith is ideal if you have simple or highly customized website requirements. Its very simple to learn and you can create your website in like an hour or two. Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.

1 comment: