将 markdown 文件作为字符串导入 Next.js

Import markdown files as strings in Next.js

如何将降价文件作为字符串导入 Next.js 以在客户端和服务器端工作?

您可以配置您的 Next.js webpack 加载器来加载 markdown 文件并 return 它们作为字符串,例如:

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.

处理

更快和“Next.js 方式”是使用插件 next-mdx

文档: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']
})

只需安装raw-loader

npm install --save raw-loader

然后编辑您的 next.config.js

 webpack: (config) => {
  config.module.rules.push({
    test: /\.md$/,
    use: 'raw-loader',
  });
  return config;
},