Tag: Storybook
Storybook + NextJs with TypeScript Paths set

Storybook + NextJs with TypeScript Paths set

Previously I have written about making your code neater by using TypeScript paths. Since then I have found that the NextJs create app Wizzard now asks you about setting this, so that from the get-go you will now likely start with it set in an application and have neater code for the better.

However, if you then try using Storybook then you're likely to see an error Module not found: Error: Can't resolve '@/components...' on any component that has an import using one of the paths.

Storybook error relating to paths

Quite simply, Storybook does not pick up the setting in your tsconfig.json file and it has no idea where to import the module from.

To get around this issue we need to also tell Storybook about the paths we've set in .storybook\main.ts. We do this by adding a resolve alias to the config returned by webpackFinal. The code example here sets an alias that will match the default path set by NextJs in its create app wizzard.

1import type { StorybookConfig } from "@storybook/nextjs";
2import path from "path";
4const config: StorybookConfig = {
5 // Other config removed for clarity
6 webpackFinal: async (config, { configType }) => {
7 if (!config.resolve) {
8 return config;
9 }
11 config.resolve.alias = {
12 ...config.resolve.alias,
13 "@": path.resolve(__dirname, "../src"),
14 };
16 return config;
17 },
19export default config;

Of course if you have other paths set then you can add them here as well. When you next run storybook the error should be gone and your components now show in Storybooks UI.