DEV Community

Praveen Puglia
Praveen Puglia

Posted on

2

How to Import Markdown Files in Vue CLI + TypeScript Projects

Recently, I came across the need to import a markdown file in a Vue component and realized that the internet is full of confusing solutions. Fiddled around for a few hours and found out that it's really quite simple.

Here's a little bit about the setup I have.

  • Vue CLI
  • TypeScript

I am also using the Vue Markdown component. What I wanted to do is

  • Write the content in a .md file.
  • Import it in my component.
  • Pass it to Vue Markdown as the source prop.

So I imported the markdown file in my component and the first thing I saw is the squiggly telling me this.

TS2307: Cannot find module './query-guide.md'.
Enter fullscreen mode Exit fullscreen mode

That's because TypeScript doesn't know where to find this module or is it even a module. To fix this, I went to shims-vue.d.ts and declared any markdown file as a module.

declare module "*.md";
Enter fullscreen mode Exit fullscreen mode

...and the squiggly was gone.

NOTE: You can do this do any kind of file. In my project I also declare all scss files to be module so I can import them directly in my component. Read more on why I do that.

Once that's sorted, I came across this.

Module parse failed: Unexpected character '#' (1:0)

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
Enter fullscreen mode Exit fullscreen mode

Which means that Webpack has no idea about how to load a markdown file as a module. Quick googling pointed out that I need to use raw-loader to get the content of the file as is.

A loader for webpack that allows importing files as a String.

I installed raw-loader as dev dependency.

yarn add -D raw-loader
Enter fullscreen mode Exit fullscreen mode

Next I needed to direct webpack to use it via vue.config.js. Here's what that configuration looks like.

module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.md$/i,
          loader: "raw-loader",
        },
      ],
    },
  },
};
Enter fullscreen mode Exit fullscreen mode

That did it for me. I was able to import markdown file in my component just like any other module and use it.

import guideContent from "./query-guide.md";
Enter fullscreen mode Exit fullscreen mode

Hope this helps you save a lot of time fiddling around.

Originally posted on praveenpuglia.com.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more