Question

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

 48  32095  48
1 Jan 1970

Solution

 2

[TypeScript][Webpack][CreateReactApp] Import file as text

It doesn't have to be txt. It can be any file extension not already handled by webpack.

If you aren't using create react app, you can just skip that step although I recommend keeping webpack config modifications into a separate file.

Otherwise, I found each of these steps to be necessary to get this working. I removed all unnecessary cruft.

You only have to do steps 1-7 one time per project.

  1. [Terminal] get into your project directory: cd ./my-app
  2. [Terminal] Install raw-loader: npm i raw-loader --save-dev
  3. [Terminal][CreateReactApp=true] Install react-app-rewired so that your custom config isn't living in node_modules: npm i react-app-rewired --save-dev
  4. [VS Code][CreateReactApp=true][package.json] change start, build and test scripts to use react-app-rewired: e.g., "start": "react-app-rewired start". If you find this too radical, find your webpage.config.js and just modify that. But that incurs the risk it will get blown away. It won't survive a round trip to GitHub, for example.
  5. [VS Code] Add global.d.ts to project src
  6. [VS Code][CreateReactApp=true] Add config-overrides.js to project root my-app
  7. [Terminal] build: yarn build
  8. [VS Code] Add text file to project: src/mydir/data.txt
  9. [VS Code][example.ts] import text file: import mytext from './data.txt'
  10. [VS Code][example.ts] use text variable normally: myFunc(mytext)
  11. [Terminal] run: yarn run

global.d.ts

declare module '*.txt' {}

config-overrides.js

module.exports = function override(config, env) {
  const newRule = {
    test: /\.txt$/i,
    loader: 'raw-loader',
    options: {
      esModule: false,
    },
  }
  config.module.rules.find((r) => r.oneOf).oneOf.unshift(newRule)
  return config
}

data.txt

hello world

example.ts

import myText from './data.txt'

var result = myFund(myText)
2023-02-01

Solution

 -3

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;
}
2019-05-19