'How to install typescript + jest with create-react-app?
I want to install typescript and jest in a create-react-app-based app. I feel that since this is such a common installation choice there must be at least one "everything just works" set of configuration steps to follow.
I initially ran npx create-react-app my-project --template typescript
. That was great for a while. I wrote several thousand lines of code with that. And then one day I decided I wanted to add some mocks to a spec file with code like this:
import jest from "jest";
jest.mock('./somemodule');
...but the "jest" instance is undefined. So I followed directions in different articles to install further devDependencies. But these seem to conflict with dependencies inside of create-react-app, suggesting that I need to focus on setting up my project correctly the "Create-react-app Way" according to its expectations.
Rather than burden StackOverflow with the details of my build and package management issues, I figure I'll just ask the simpler question - what is the correct way to set up create-react-app+typescript+jest in a way where it doesn't have a bunch of irritating, random problems?
And then after I've followed this advice, if I still have problems, I might ask a second, separate SO question with specific details.
Solution 1:[1]
The command below should create a new React project supporting Typescript and Jest without need of further modification.
npx create-react-app my-app --template typescript
Details about the above command can be found here: https://create-react-app.dev/docs/adding-typescript/
The above command will set up a new project. But if, like me, you have an existing create-react-app
project with issues like:
- the Jest module is undefined or doesn't seem to have expected functions
- your
npm run start
andnpm run build
fail due to conflicting dependencies - or you just want to get to a "standard" package.json configuration without all the hassle of copying your source into a new project.
...you can use the process below to fix/upgrade your package.json:
- Use the same
npx create-react-app my-app --template typescript
command above to create a separate working ("Good") project with all the right dependencies. This project will just be used as a reference. - Compare the package.json of the Good project to the non-working ("Bad") project, and make sure the Bad package.json has the same modules and version#s as the Good package.json. You probably don't have to delete any modules in the Bad package.json that aren't in the Good package.json.
rm -rf node-modules
in the Bad project.rm package-lock.json
in the Bad project.npm install
in the Bad project.
Self-answering for posterity.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Erik Hermansen |