1

I am trying to incrementally build a React site with the content written in Markdown.

I am stuck so far as I am trying to import a single Markdown file with Frontmatter to render.

I have tried front-matter-loader and raw-loader; both throw errors:

/pages/home.md: Invalid left-hand side in prefix operation (1:2)
1 | ---
  |   ^   
2 | title: This is the home page  
3 | ---

Here is my simple JavaScript test:

import home from '../pages/home.md';

console.log('testing');
console.log(home);

Here are my loaders in the webpack config:

...
module: {
    rules: [
        { 
            test: /\.(js)$/, 
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['env'],
                    cacheDirectory: '.babel_cache'
                }
            }
        },
        {
            test: /\.md$/,
            use: 'raw-loader'
        }
    ]
},
...

What I expected from using raw-loader was a string, which I could then pass to front-matter, extract, and then render HTML with marked. However, I obviously cannot seem to require/import the file properly. My next tests will be to remove the webpack loaders altogether and try to use node's fs to read the file. I wondered if anyone would be able to help me spot any error here.

I keep thinking, the front-matter-loader is not a complicated file at all (view here), and there's no reason why it shouldn't load the file.

Thanks for any insight.

2 Answers 2

2

From reading the front-matter-loader docs, looks like you need to pass the results from front-matter-loader through a json-loader or extract the front-matter data and markdown separately. Assuming you've installed the json-loader, front-matter-loader, and raw-loader packages, the following might work.

Passing front-matter-loader results through json-loader in your webpack config:

    ...
    module: {
        rules: [
            ...
            {
                test: /\.md$/,
                use: ['json-loader', 'front-matter-loader']
            }
        ]
    },
    ...

Extracting the front-matter data and markdown separately:

var data = require('json!front-matter!../pages/home.md')
var content = require('raw!front-matter?onlyBody!../pages/home.md')
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the front-matter module.

Installation

npm install front-matter

OR

yarn add front-matter

Usage

var fs = require('fs')
  , fm = require('front-matter')

fs.readFile('path/to/markdown-file.md', 'utf8', function(err, data){
  if (err) throw err

  var content = fm(data)

  console.log(content)
})

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.