How do you import a text file into typescript?

[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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)