One of the first tasks that I had in my actual job was to integrate a documentation platform for our components/good practices, etc. We’re using Next.js and my first insight was Styleguidist. I had struggles to make it work, but at the end was easier than I thought
So, in this post I’m gonna show you how I made it work.
First of all, I’m not gonna show you how to configure all the Next app, so I made this repository where you can see the final and the initial app. To start you can go to this branch and clone it.
Let’s see what we have in the branch that we have cloned. We have a ´docs´ folder in the root where our styleguidist project lives, it’s all configured to work by itself. But we need to make some changes to integrate it with next.
Understanding the /docs folder
At this point I assume you have cloned the branch that I told you lines above, so in this project we have a /docs. This folder contains the styleguidist project and configuration.
Add the next.js page
We need to create a new page on Next.js, so in order to do it, we need to create a new file inside the ‘pages’ directory called: ‘docs.js’. This will tell Next.js that the route /docs will read our file.
Inside that file we need to make a functional component (we don’t need more). like this:
Basically what we’re creating here is this:
A root div template where styleguidist is gonna be mounted, and the script that it’s gonna make it happen. And after that telling Next.js to just inner that html in our app (route).
There’s two tricky thing in the code we just wrote, one is we’re asking for a build/bundle and we have a custom server on our app, so we need to configure our server so it can serve that file, otherwise it wont’t work.
We’re using express.js in the custom server, so we need to add a route to serve our build file
Let’s add these lines, basically what we’re doing is:
Styleguidist generates an id for every bundle, but we’re catching that with the /:id.
After that, we look for the build file inside the styleguidist build, and we serve it to the client.
With that, you can go to http:localhost:3000/docs and you’ll see this:
In the repo you can see the master branch for the full code.