How can I import markdown files as strings in Next.js to work on client and server side?
js by integrating MDX. "What is MDX?" You might ask me. Well... MDX is more or less like the markdown files we always see in GitHub repositories. MDX brings this flexibility into a markdown file by allowing you to literally write or import JavaScript (React) components into your articles.
To recap, in a typical javascript framework (such as Gatsby or Next. js) project structure, both the require and import statements can be used inside the src directory as those files are to be transformed, compiled, and bundled using Babel and Webpack later in the build process for production.
You can configure your Next.js webpack loaders to load markdown files and return them as strings, for example:
docs/home.md
# Home
This is my **awesome** home!
pages/index.js
import React from 'react';
import markdown from '../docs/home.md';
export default () => {
return (
<div>
<pre>{markdown}</pre>
<small><i>Import and render markdown using Next.js</i></small>
</div>
);
};
package.json
{
"name": "example",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"file-loader": "^1.1.6",
"next": "^4.2.1",
"raw-loader": "^0.5.1",
"react": "^16.2.0",
"react-dom": "^16.2.0"
}
}
next.config.js
module.exports = {
webpack: (config) => {
return Object.assign({}, config, {
externals: Object.assign({}, config.externals, {
fs: 'fs',
}),
module: Object.assign({}, config.module, {
rules: config.module.rules.concat([
{
test: /\.md$/,
loader: 'emit-file-loader',
options: {
name: 'dist/[path][name].[ext]',
},
},
{
test: /\.md$/,
loader: 'raw-loader',
}
]),
}),
});
}
};
When running:
$ npm run dev
Something like this would appear:
With the markdown string you can do whatever you would like. For example, process it with marksy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With