Webpack raw-loader errors out when require markdown file

940 Views Asked by At

raw-loader errors out when attempting to require any .md file.

Adding raw loader to import markdown files:

  test: /\.md$/i,
      use: [{
        loader: 'raw-loader',
        options: {
          esModule: false
        }
      }],

In .js file, require the markdown file..

return require(postPath)
// postPath is '../posts/awards.md'
Error: Cannot find module '../posts/awards.md'
at webpackEmptyContext (eval at <path to file>)
....

the path to markdown file is the relative path: /posts/awards.md

If I change awards.md to awards.json it works. So maybe it is an issue with raw-loader looking for a export in awards.md and not find one, thus erroring out? Isn't the point of esModule: false to instruct Webpack to NOT treat it as module?

1

There are 1 best solutions below

1
On

Seems like you're having the same problem as this person.

Quoting an answer:

Webpack performs a static analyse at build time.

It doesn't try to infer variables which that import(test) could be anything, hence the failure.

It is also the case for import(path+"a.js").

If you need truly dynamic imports, you have to restrict it to a known path:

import("./locales/" + locale + ".js")

I re-created your problem and sure enough:

function test(mod) {
    return require(mod)
}

console.log(test("./test.md"))

Doesn't work. HOWEVER this works:

function test(mod) {
    return require("./" + mod)
}

console.log(test("test.md"))

So it should suffice to change your code to this:

return require("../" + postPath + ".md")

And change postPath to:

// postPath is 'posts/awards'