Reputation: 4885
I would like to load a markdown file from the current directory as a string, use case:
import { State } from "markup-it" ;
import markdown from "markup-it/lib/markdown";
import bio from './Bio.md'
const mdParser = State.create(markdown);
const bio_o = mdParser.deserializeToDocument(bio);
// tried this next: but cannot import files system because react stubbed it out
const fs = require('fs');
When I import bio from './Bio.md'
I get path to file, not a string format. So next I try using the file system fs
a la : require file as string but apparently fs
has been stubbed out by react. So now I am completely stumped in terms of how I can import a file from the file system as a string. Am I missing something conceptually here? is it because I'm on the client side?
Upvotes: 1
Views: 5223
Reputation: 715
If you're fine bundling the markdown text in with your client app code, you can just stick raw-loader into your setup and tell webpack to apply it to anything ending matching /\\.md$/i
, that would let you use mdParser
on the client side. This presumes of course that Bio.md
is in the same folder as this JS file during build time.
If you want the client to load the markdown from the server and parse it then, you're back to what Rohith Murali said about fetch/axios.
Setting up raw-loader to do this is really easy, as shown right in their readme:
Installation is thankfully straight forward, unlike some modules they didn't need to do anything funny with the name.
npm install raw-loader --save-dev
Then you configure webpack to load markdown files using the newly installed loader:
// webpack.config.js
module.exports = {
// ...
module: {
rules: [
// new rule: anything ending with ".md" is loaded with raw-loader
{
test: /\.md$/i,
use: 'raw-loader'
},
// any other rules...
],
// ...
},
// ...
}
Then just import your MD file as usual and get back a string:
import bio from './Bio.md';
const bio_o = mdParser.deserializeToDocument(bio);
Upvotes: 2
Reputation: 5669
Yes. I think you are missing something conceptually. When you build a react application and the user's browsers try to run your js the filesystem will be refering to the user's machine. But what you actually want is a file residing in the static server. Two things can be done,
Upvotes: 2