Sapper/Svelte: How do I add markdown files?

Viewed 3173

I am creating a blog using Sapper using the default sapper-template-rollup.

In the blog folder, it does mention about generating data from markdown files. But I can't find how to do it?

4 Answers

I published https://github.com/mikenikles/sapper-template-with-markdown which shows how to use the default Sapper template, but uses *.md files for the blog post content.

The main change was in src/routes/blog/_posts.js where I replaced the content with:

const fs = require('fs');
const frontMatter = require('front-matter');
const marked = require('marked');

const posts = fs.readdirSync('./src/posts').map(postFilename => {
  const postContent = fs.readFileSync(`./src/posts/${postFilename}`, {
    encoding: 'utf8'
  });
  const postFrontMatter = frontMatter(postContent);
  return {
    title: postFrontMatter.attributes.title,
    slug: postFrontMatter.attributes.slug,
    html: marked(postFrontMatter.body)
  }
});

posts.forEach(post => {
    post.html = post.html.replace(/^\t{3}/gm, '');
});

export default posts;

Then, each blog post is stored in src/posts as a Markdown file with the following format:

---
title: 'What is Sapper?'
slug: 'what-is-sapper'
---

Your markdown content.

Update 2020-06-14:

There is a GitHub version as well now (since 2019-11-11) that publishes with Netlify and has a custom domain added. So unlike the GitLab version, it does not use Sapper's base URL to alter the base path that is necessary with GitLab and GitHub pages unless you add a custom domain.

Original answer 2019-10-24:

You may find this repo helpful. I also have an open PR on the Sapper Template repo, first revising the old Markdown branch in Jan. 2019 and then adding Svelte 3 support in May 2019, but it is probably easier to look at and clone my repo on GitLab, plus it has more current dependency updates I have not added to the PR yet.

You might have more lick using MDsveX which is a Svelte Markdown processor, created by one of the core community members.

However yes, you can also just use marked or snarkdown (which is what I use), the same way as you would use any other library - simply import it and pass your markdown code to it.

I went with @Antony Jones's approach. I put the .md files in my routes/ folder and used Svelte Preprocess Markdown, setting it up in my rollup config to process .md files (turning them into .svelte files). The .md files are organized into sub-folders within the routes/ folder, and each folder has an index page that will list links to the pages made by the files or folders inside. Here is a link to the repo if you want to check it out: link. It is still a work in progress.

As @rdela said in his comments, though, this approach is less flexible than processing the posts using your own code to get the front matter as they do in the template repo, and then filtering the posts, putting them into folders based on tags in their front matter, or something like that.

Related