Using node and metalsmith

In my previous post on Metalsmith, I explained how to get up and running with Metalsmith. I used a metalsmith.json configuration file. But it is also possible to use a javascript file and let NodeJS run it.

Take this metalsmith.json file for example:

{
  "source": "src",
  "destination": "build",
  "plugins": {
    "metalsmith-drafts": true,
    "metalsmith-markdown": true,
    "metalsmith-layouts": {
        "engine": "handlebars",
        "partials": "partials"
      }
  }
}

This can be mapped to the following javascript file:

var Metalsmith = require('./node_modules/metalsmith'),
    drafts     = require('./node_modules/metalsmith-drafts),
    markdown   = require('./node_modules/metalsmith-markdown),
    layouts    = require('./node_modules/metalsmith-layouts);

Metalsmith(__dirname)
  .source('./src')
  .destination('./build')
  .use(drafts())
  .use(markdown())
  .use(layouts({
    engine: 'handlebars',
    partials: 'partials'
  }))
  .build(function(err) {
    if (err) throw err;
  });

Save this to index.js and you can simply run node index from the command line. The results would be the same.

The advantage of using a javascript file, of course, is that you can add more logic to it.

If you're running node 0.12.x, you'll get an unexpected token error. That's because Metalsmith is using ES6 syntax, and node currently doesn't support it by default. The solution is very simple.

Either use the node --harmony index command, or install the Harmonize package (npm install harmonize --save-dev), add it to your index.js and call it before anything else:

require('./node_modules/harmonize)();

var Metalsmith = require('./node_modules/metalsmith'),
    drafts     = require('./node_modules/metalsmith-drafts),
    markdown   = require('./node_modules/metalsmith-markdown),
    layouts    = require('./node_modules/metalsmith-layouts);

Metalsmith(__dirname)
  .source('./src')
  .destination('./build')
  .use(drafts())
  .use(markdown())
  .use(layouts({
    engine: 'handlebars',
    partials: 'partials'
  }))
  .build(function(err) {
    if (err) throw err;
  });

Notice how I'm requiring Harmonize and immediately executing it on the same line.

This last option is preferable because you can just run node index again.

I'm still using it to build my company's site, so you can check out the code in the GitHub repository.