Estee Tey
Estee Tey

Reputation: 21

How to import a markdown file in a typescript react-native project?

I have tried to import a markdown file into my typescript react-native project in 2 ways.

import * as readme from "./sample.md"
import readme from "./sample.md"  

Both didn't work. So I found a similar issue reported previously and mentioned about making a typings.d.ts file for declaring modules, and i've tried this as well but it still doesn't work.

declare module "*!txt" {
    const value: any;
    export default value;
}

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

EDIT: There is no import error on Vscode but on the react-native app itself, it says that it cannot find module './sample.md' as it is only looking for (.native|.ios|.json|.ts etc) files.

Any help would be appreciated, been stuck on this for far too long. Thank you!

Upvotes: 2

Views: 3122

Answers (1)

Pramod Mali
Pramod Mali

Reputation: 1798

  1. Create one type definition (index.d.ts) file in one of the project directory and put the following code.
declare module "*.md";
  1. Add tsconfig.json -> CompilerOptions -> typeRoots as following
{
     "compilerOptions": {
         ...
         "typeRoots": [ "<types-directory-created-in-#1>", "./node_modules/@types"],
         ...
     }
}
  1. In your component
import React, { useEffect, useState } from 'react';
import readme from 'path/filename.md';

export default function ComponentName() {
    const [md, setMD] = useState("");

    //Use componentDidMount(): if class based component to load md file
    useEffect(() => {
        fetch(readme)
            .then(data => data.text())
            .then(text => {               
                setMD(text);
            })
    }, []);

    return (
        <div>{md}</div>
    )
}

Upvotes: 2

Related Questions