Create React App is a fantastic way to get up and running building a web app with React. It also supports using TypeScript with React. Simply entering the following:
Will give you a great TypeScript React project to get building with. There's two parts to the TypeScript support that exist:
- Type checking AKA "seeing if our code compiles". Create React App uses the
fork-ts-checker-webpack-pluginto run the TypeScript type checker on a separate process and report any issues that may exist.
This is a great setup and works very well for the majority of use cases. However, what if we'd like to tweak this setup? What if we'd like to swap out
ts-loader for compilation purposes? Can we do that?
Yes you can! And that's what we're going to do using a tool named
CRACO - the pithy shortening of "Create React App Configuration Override". This is a tool that allows us to:
Get all the benefits of create-react-app and customization without using 'eject' by adding a single
craco.config.jsfile at the root of your application and customize your eslint, babel, postcss configurations and many more.
So let's do the swap. First of all we're going to need to add
ts-loader to our project:
Then we'll swap over our various
scripts in our
package.json to use
Finally we'll add a
craco.config.js file to the root of our project. This is where we swap out
So what's happening here? The script looks for
You cannot remove a single loader using
babel-loader. We'll also add
ts-loader with the
transpileOnly: true option set (to ensure
ts-loader doesn't do type checking).
Now the next time we run
npm start we'll have Create React App running using
ts-loader and without having ejected. If we want to adjust the options of
ts-loader further then we're completely at liberty to do so, adjusting the
options in our
"sourceMap": true property in your
Finally, if we wanted to go even further, we could remove the
fork-ts-checker-webpack-plugin and move
ts-loader to use
transpileOnly: false so it performs type checking also. However, generally it may be better to stay with the setup with post outlines for performance reasons.