简体   繁体   中英

How do I read raw contents of markdown file into string using webpack 5 and docusaurus

I am currently refactoring a Docusaurus app that displays developer documentation from markdown docs. The app has a "quick start" feature which has a wizard that users fill out info and then it populates a markdown template.

The app used to use webpack 4 and raw-loader to read the contents of an documentation template and then do a find and replace with what the user passed in. Ever since I switched to webpack 5, raw-loader no longer works. I read in webpack 5 that the use of raw-loader was no longer necessary as that functionality is built into webpack; https://webpack.js.org/guides/asset-modules/#source-assets

I created a webpack.config.js file:

module.exports = {
  module: {
    rules: [
      {
        resourceQuery: /raw/,
        type: 'asset/source'
      }
    ]
  }
};

I have a markdown file /docs/template.md :

# My template

## Some section 1

some text

## Some section 2

some text

And in my js file I attempt to import the contents like so:

import template from '@site/docs/template.md?raw';

console.log(template);

However webpack is not loading the contents of markdown file as a string, I get some mdx content:

ƒ MDXContent(_ref){let{components,...props}=_ref;return
(0,_mdx_js_react__WEBPACK_IMPORTED_MODULE_2__.mdx)(MDXLayout
(0,_Users_kevin_apps_docs_node_modules_babel_runtime_helpers_esm_ext…

Any idea on what I am doing wrong?

I don't think Docusaurus sites respect webpack.config.js files, so I resolved this issue with an inline plugin module in docusaurus.config.js :

/** @type {import('@docusaurus/types').Config} */
module.exports = {
  // ...other configs...,
  plugins: [
    // ...other plugins...,
    () => ({
      name: 'my-raw-loader',
      configureWebpack() {
        return {
          module: {
            rules: [
              {
                resourceQuery: /raw/,
                type: 'asset/source',
              },
            ],
          },
        };
      },
    }),
  ],
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM