2

Im using the static render feature of NextJS to generate a static version of my site thus I want to ensure that on the very first render of the page all the data it needs to render correctly is supplied.

I have a number of blog posts which I have stored as .md files in /static and want to access them in a page such as:

import * as fs from "fs";
...

export default class extends React.Component<IProps, any> {

  static async getInitialProps (props: IServerProps) {
    const post = (await getDb()).posts.find(p => p.id == props.query.id);
    const markdown = fs.readFileSync(`/static/posts/${post.markdownFileName}`);
    return { post, markdown }
  }
...

But if try to run the above I get the following error:

This dependency was not found: * fs

So im not sure how I should go about accessing these static resources while on the server..

6
  • 1
    Rather than using fs, have you thought about something like markdown-loader and then import/require the .md file? Next.js allows some customization of the Webpack configuration: github.com/zeit/next.js/#customizing-webpack-config Commented Dec 5, 2017 at 23:39
  • @MattHolland unfortunately I cant do that, according to the docs I cant use webpack loaders on the server side and that I cant use markdown-loader :( Commented Dec 6, 2017 at 10:46
  • Which docs tell you that? Commented Dec 6, 2017 at 17:52
  • 1
    You are correct, I don't know how I missed that! It does say that babel plugins can be used and there is one for MD content: npmjs.com/package/babel-plugin-markdown Commented Dec 7, 2017 at 0:44
  • 1
    @MattHolland yes I saw that we can use babel but I wasnt sure which of the plugins to go for, this one doesnt have many downloads but I guess thats okay? Its good that it has an option not to convert the md to html too. Thanks, you should turn this into an answer so I can accept it. Commented Dec 8, 2017 at 1:48

1 Answer 1

1

Unfortunately Next.js doesn't allow the use of webpack loaders to handle different file types on the server (Although they are used to build the client-side bundles), but it is possible to use a Babel plugin. One such plugin for Markdown content can be found here: https://www.npmjs.com/package/babel-plugin-markdown

After configuring it in .babelrc:

{
  "plugins": ["markdown"]
}

it's possible to use markdown.require() to pull in .md content:

const html = markdown.require('./foo.md')

More options are described at the link!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.