NextJS is one of the most important, widely-used, and reliable frameworks for server-side rendering and production with React. This, combined with the ability to integrate TypeScript into your NextJS project makes it all-the-more great to use.
But how exactly do you go about doing so?
In order to generate our boilerplate Next starter code, run the following command in your terminal:
yarn create next-app
NOTE: You can always use NPM's
npx create-next-app, but we will be utilizing Yarn over the course of this project and walkthrough.
After you run the initial script, the CLI will prompt you with the following question:
? What is your project named? >
After you type in the name of your project and press Enter, you'll be good to go! (at least for the basic NextJS setup).
You can now test that the setup has gone smoothly by running
yarn dev in your command-prompt and opening the port (usually
localhost:3000, on a browser:
cd my-app yarn dev
In order to implement TypeScript into our NextJS project, we must first create. a
tsconfig.json file. Having this file automatically tell NextJS that the root directory is one of a TypeScript project. To put it simply, the presence of a tsconfig.json file in a project indicates that TypeScript is present as well.
How do we go about creating one? Simply run this command in the root directory of your project:
Install all required dependencies for TypeScript and NextJS by running the following command in your terminal:
# If you're using NPM npm install --save-dev typescript @types/react @types/node # If you’re using Yarn yarn add --dev typescript @types/react @types/node
Now, pause your server (
Ctrl+C) and start it back up again by using
As you do so, you will notice that NextJS has automatically detected TypeScript in your project (due to the tsconfig.json file that we created earlier).
Now that TypeScript is properly set up in our project, we can now use it to program our app.
pages directory of your project into TypeScript (REMEMBER:
filename.tsx for React).
You are now ready to enjoy the benefits of using TypeScript inside of your NextJS app.