Skip to content

Advanced example with markdown and syntax highlighting

ismay edited this page Jul 25, 2018 · 2 revisions

You can use metalsmith-in-place with metalsmith's javascript API or the CLI. For this example we'll use the javascript API:

Install metalsmith and metalsmith-in-place:

$ npm install metalsmith metalsmith-in-place

Install remaining dependencies

Since we're using markdown we'll need to install a markdown jstransformer. For this example we'll use marked, so we'll also need to install jstransformer-marked. And finally, for the highlighting we're using highlight.js:

$ npm install jstransformer-marked highlight.js

Configure metalsmith

We'll create a build script and a markdown file for metalsmith-in-place to process:

./build.js

const metalsmith = require('metalsmith');
const inPlace = require('metalsmith-in-place');

metalsmith(__dirname)
  .source('src')
  .destination('build')
  .use(inPlace({
    engineOptions: {
      highlight: code => require('highlight.js').highlightAuto(code).value
    }
  }))
  .build(error => {
    if (error) throw error;
  });

As you can see, we're setting the engineOptions option for metalsmith-in-place. The engineOptions will be passed on to the jstransformers we're using, which in this case is jstransformer-marked. We're using the code highlighting example from the marked documentation.

./src/index.md

Below is a code block, indicated by the three backticks:

```javascript
const variable = "value"
console.log(variable);
```

Build

To build just run the build.js build script:

$ node build.js

Which will output the following file:

./build/index.html

<p>Below is a code block, indicated by the three backticks:</p>
<pre><code class="lang-javascript">const <span class="hljs-keyword">variable</span> = <span class="hljs-string">"value"</span>
console.log(<span class="hljs-keyword">variable</span>);
</code></pre>