【问题标题】:Import markdown files as strings in Next.js在 Next.js 中将 markdown 文件作为字符串导入
【发布时间】:2017-12-23 17:08:30
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs markdown next.js


    【解决方案1】:

    你可以配置你的 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 处理它。

    【讨论】:

      【解决方案2】:

      更快的“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']
      })
      
      【解决方案3】:

      只需安装raw-loader

      npm install --save raw-loader
      

      然后编辑你的 next.config.js

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-22
        • 1970-01-01
        • 1970-01-01
        • 2021-02-05
        • 1970-01-01
        • 2018-01-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多