2

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!

1 Answer 1

2
  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>
    )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.