In this post I will show you how to setup a basic next.js app that uses TypeScript and also Storybook.
Create a next.js app
Add TypeScript
Add Storybook
Create a next.js app
Add the following scripts into the package.json:
Add a page to the nextjs app:
Test the nextjs app by running:
Add Typescript
First install the module:
Then create a next.config.js in the root folder:
Now you can rename the pages/index.js to pages/index.tsx. When you run npm run dev you will notice it still works. Now you can use TypeScript in your pages and components.
Add Storybook
The first thing to do is to simply add the base dependencies for storybook:
Also add some @types:
No you can add the npm script to start storybook:
Running storybook will result in an error since we have not yet created a storybook config file. We add this file within a new folder called .storybook (note the '.' in the folder name):
This way we specify to have files with the *.stories.tsx file ending inside a components folder. Of course you can specify the location of your story files however you like.
Let's create a simple component and a story next.
The story looks like this:
When we start our storybook now, we will see an issue saying that we need an appropriate loader to handle this file type. In order to solve this issue we need to create a custom webpack config for storybook. Add this webpack.config.js file inside the .storybook folder:
Make sure to also install this package:
Story book will now be able to use TypeScript, but it cannot use it from the TypeScript package installed by next.js. So we need to add it:
You will also need a TypeScript config. You can add this one to the root folder. Make sure its named tsconfig.json:
Finally to make next.js run without TypeScript issues, you need to setup a .babelrc file like this: