Today I Made Webpack Load Markdown!

disclaimer: nothing I do on this site is professionally done. It's always pretty much a better idea to just read the docs

This tutorial assumes you can work your way around webpack decently and are using babel-loader for es6. I prefer using Gaeron's markdown-hot-boilerplate

I have always liked flat file layouts to blogs and webpages. I have always figured the least amount of work done via a database the better. It's always been a mantra to avoid using a database whenever I don't need one. Today I wanted to learn how to load local markdown files into webpack and display them in react.

To do this I needed to learn how to use loaders in Webpack....More specifically I needed to use markdown-loader. It was surprisingly simple to setup with just very few quirks.

One thing to note is that markdown-loader actually pre-parses your markdown files to html. This means that when we are loading them into react we will need to dangerously set our innerhtml. No big deal really I'll show you how to do that later.

The first thing we will want to do is go ahead and....

//install markdown-loader
npm install --save markdown-loader

After installing the markdown-loader we will need to configure into our webpack.config.js loader's section.

//append to our loader
{
  module: {
    loaders: {
       { test: /\.md$/, loader: "html!markdown?gfm=false" },
        ]
    }
}

Sidenote: you must have the html loader installed in your webpack in order for this to work.

For this example I am going to bypass the github flavored markdown option and stick to previty. Great! We now have the ability to utilize:

import file from 'markdown.md';

Let's make a component displaying our markdown file! Since markdown-loader already pre-parses our markdown file we now have the ability to simply load it into our components(or change the state to a new component)!

Try this out:

//import our component
import React, { Component } from 'react';

//Here we import our markdown file 
import markdownFile from 'markdown.md';

export default class testComponent extends Component {  
    rawMarkup(){
           return{ __html: markdownFile};
    }
    render(){
           return(
             <div dangerouslySetInnerHTML={this.rawMarkup()} />
            );
   }
}    

We know React is not a huge fan of utilizing dangerouslySetInnerHTML, but when we are rendering markup, and it is encased in a function it's somewhat safe. We now have created a component that will read from a static markdown file, and output to the screen.

When testComponent is rendered we will now have our markdown file rendered into nice and tidy html!