How to import markdown (.md) file in typescript

I am trying to import readme files in typescript, but I get the message "error module not found"

My TS code

import * as readme from "./README.md"; // here i am getting error module not found

      

I also tried: typings.d.ts

declare module "*.md" {
    const value: any;
    export default value;
}

      

I found that in typescript 2.0 https://github.com/Microsoft/TypeScript/wiki/What 's-new-in-TypeScript # typescript-20 they introduced "wildcard in module names" using which we can include any file extension.

I just followed the example https://hackernoon.com/import-json-into-typescript-8d465beded79 which is for json files. I have followed the same for markdown files but with no success.

I am not using webpack and any kind of loader, so I just wanted it from typescript only

+6


source to share


3 answers


In your linked example, they are importing JSON, not Markdown. They can import JSON as valid JSON is also valid JavaScript / TypeScript. Markdown is not valid TypeScript and therefore imports of this type simply won't work out of the box.

If you want to access the Markdown file at runtime, make an AJAX request to fetch its content. If you really want it to be embedded in your JavaScript, you'll need some sort of assembly script. You mentioned that you are not using Webpack, but you can achieve what you are looking for by adding a module rule that binds /\.md$/

to raw-loader

. You will need to use some equivalent.

Edit:

You seem to learn something new every day. As the OP points out in the comments, TypeScript 2.0 has support for importing resources without code.



Try the following:

declare module "*!txt" {
    const content: string;
    export default content;
}

import readme from "./README.md!txt";

      

The value readme

must be a string containing the contents of README.md.

+5


source


@ Mitch's answer didn't work for me. Using angular v7 I found that I could just use this syntax:import * as documentation from 'raw-loader!./documentation.md';



+1


source


For those using React with Typescript:

Create a globals.d.ts file in the root directory with the following code:

declare module "*.md";

      

then import it like this:

import readme from "../README.md" // substitute this path with your README.md file path

      

0


source







All Articles