How can I import markdown files as strings in Next.js to work on client and server side?
Asked
Active
Viewed 7,340 times
3 Answers
11
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.
Romel Pérez
- 554
- 4
- 16
7
Quicker and "Next.js way" is to use plugin next-mdx
Documentation: https://github.com/vercel/next.js/tree/canary/packages/next-mdx
// next.config.js
const withMDX = require('@zeit/next-mdx')({
extension: /\.mdx?$/
})
module.exports = withMDX({
pageExtensions: ['js', 'jsx', 'mdx']
})
icc97
- 10,009
- 8
- 64
- 83
piecioshka
- 3,945
- 2
- 19
- 29
-
2Documentation is now located at https://github.com/vercel/next.js/tree/canary/packages/next-mdx – rose specs Jul 04 '21 at 15:55
3
Just install raw-loader
npm install --save raw-loader
then edit your next.config.js
webpack: (config) => {
config.module.rules.push({
test: /\.md$/,
use: 'raw-loader',
});
return config;
},
sidonaldson
- 22,548
- 10
- 51
- 59