[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.
- [Terminal] get into your project directory:
cd ./my-app
- [Terminal] Install
raw-loader
: npm i raw-loader --save-dev
- [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
- [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.
- [VS Code] Add
global.d.ts
to project src
- [VS Code][CreateReactApp=true] Add
config-overrides.js
to project root my-app
- [Terminal] build:
yarn build
- [VS Code] Add text file to project:
src/mydir/data.txt
- [VS Code][example.ts] import text file:
import mytext from './data.txt'
- [VS Code][example.ts] use text variable normally:
myFunc(mytext)
- [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)