typescript

How do you import a text file into typescript?


As a minimal example, I want to import a text file into typescript and print it to the console without reading it using fs. Something like this:

import text from './foo.txt'

console.log(text)

I've found many examples of solutions, such as this one and I have created a typings.d.ts file with the content

declare module '*.txt' {
  const content: string;
  export default content;
}

But when I build the project I still see "error TS2307: Cannot find module './foo.txt'."

What am I missing?

Example repo here: https://github.com/gferreri/typescript-import-test


Solution

  • If the text file is a graphql schema, as noted in your comment, you can use graphql-tag/loader with webpack. Couple that with proper typing for *.graphql files:

    declare module '*.graphql' {
      import { DocumentNode } from 'graphql';
      const value: DocumentNode;
      export = value;
    }