如何在Next.js中将markdown文件导入为字符串,以便在客户端和服务器端工作?
答案 0 :(得分:4)
您可以配置Next.js webpack加载器以加载markdown文件并将其作为字符串返回,例如:
<强> 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',
}
]),
}),
});
}
};
运行时:
$ npm run dev
会出现这样的事情:
使用降价字符串,您可以做任何您想做的事情。例如,使用marksy处理它。
答案 1 :(得分:1)
更快和“ Next.js方式”是使用插件 next-mdx
文档:https://github.com/zeit/next-plugins/blob/master/packages/next-mdx/readme.md
// next.config.js
const withMDX = require('@zeit/next-mdx')({
extension: /\.mdx?$/
})
module.exports = withMDX({
pageExtensions: ['js', 'jsx', 'mdx']
})
答案 2 :(得分:0)
只需安装raw-loader
npm install --save raw-loader
然后编辑你的 next.config.js
webpack: (config) => {
config.module.rules.push({
test: /\.md$/,
use: 'raw-loader',
});
return config;
},