Storybook Can't Find Components in React, Next.JS, Typescript Project
Asked Answered
U

7

9

I have storybook setup with my next.js, typescript and react project. The project renders fine but storybook breaks and give me the me error: "Module not found: Error: Can't resolve 'components/atoms' in...." It seems like the path to components is causing it to break:

import { Element } from 'components/atoms';

but the following works:

import { Element } from '../../atoms

I have a tsconfig.json file with the following:

  "compilerOptions": {
    "baseUrl": "src",
    },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx"
  ],
...

I tried some of the suggestions online but none seems to resolve the path issue. I created a webpack.config.js in my .storybook folder with the following, but still get errors.

module.exports = {
 ...
  resolve: {
    modules: [path.resolve(__dirname, 'src'), 'node_modules']
  }
};

I would like to not use the ../../ when calling files and just be able to use the ./components structure.

Undersecretary answered 17/9, 2020 at 14:26 Comment(6)
What is your structure repo?Laevo
Updated the question with the structure of the repoUndersecretary
You seemingly have to add .storybook/main.js to configure you webpack by adding an alias to your ./src/componentsLaevo
I have a .storybook/main.js file it has configs for stories and addons. I would add an alias here to my `./src/components' to this file? Would I still need the webpack.config.js in this case?Undersecretary
Here is the way you add your alias to storybook.js.org/docs/react/configure/…. You don’t need your webpack.config.jsLaevo
Thank you, that worked by adding the webpackFinal code as suggested by them to my main.js and adding path.resolve('./src/') to the config they provided.Undersecretary
P
17

Spent some time fighting with Storybook )

Here is my .storybook/main.js version, that finally worked:

const path = require("path");

module.exports = {
  webpackFinal: async (config, { configType }) => {
    config.resolve.modules.push(path.resolve(__dirname, '../src'));

    return config;
  },

  stories: [
    "../src/**/*.stories.mdx",
    "../src/**/*.stories.@(js|jsx|ts|tsx)"
  ],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/preset-create-react-app"
  ]
}
Passivism answered 18/1, 2021 at 10:28 Comment(0)
J
3

For someone who is still looking for a solution, try adding the below inside your webpackFinal before returning config. It is because storybook isn't configured to access files using absolute paths.

config.resolve.modules = [...(config.resolve.modules || []), path.resolve('./')]
Julienne answered 11/1, 2022 at 10:45 Comment(0)
C
1

None of the answers above worked for my NPM workspace project.

What was causing the issue for me was vscode started using imports from src like this:

import { MyComponent } from "src/components/Mycomponent";

but what I found works with storybook is relative imports like this

import { MyComponent } from "../components/Mycomponent";

You can make vscode use relative imports by default by setting the below (see this answer)

"typescript.preferences.importModuleSpecifier": "relative"
Cruse answered 13/9, 2023 at 14:31 Comment(0)
K
1

If you have setup Storybook with Typescript (I'm also using NextJs but I think that's irrelevant here), the webpack alias change didnt work for me.

I had this error for anything insight my components directry. eg @/components/IconType

I was missing this from the tsconfig.json, which makes sense that Storybook didn't understand the base directory for where to look:

"baseUrl": ".",

Hope that helps others

Katiekatina answered 9/10, 2023 at 10:19 Comment(0)
U
0

I was having an issue resolving aliases

Error: Can't resolve '@foo/bar'

In root > .storybook/main.js I added the property config.resolve.alias

const path = require('path');

module.exports = {
  stories: ['../libs/feature/src/**/*.stories.@(js|jsx|ts|tsx)'],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
    '@storybook/addon-interactions',
  ],
  framework: '@storybook/react',
  webpackFinal: async (config, { configType }) => {
    config.resolve.alias = {
      ...config.resolve.alias,
      '@foo/bar': path.resolve(__dirname, '../libs/bar/src/'),
    };

    return config;
  },
};
Uball answered 21/9, 2022 at 14:42 Comment(0)
O
0

I faced a different situation, but similar error after initial installation. Noting here for others using SWC (I am personally using SWC exclusively, and storybook's default webpack configuration):

Error Message:

ERROR in ./src/stories/Header.stories.ts 2:0-37
Module not found: Error: Can't resolve './Header.js' in ...\src\stories'

Solution: Simply configure swc in .storybook/main.[ts|js], as it appears there is no default configuration (console.log returns {}).

import type { Options } from '@swc/core';
// Replace your-framework with the webpack-based framework you are using (e.g., react-webpack5)
import type { StorybookConfig } from '@storybook/your-framework';

const config: StorybookConfig = {
  framework: {
    name: '@storybook/your-framework',
    options: {},
  },
  swc: (config: Options, options): Options => {
    return {
      ...config,
      // Apply your custom SWC configuration
    };
  },
};

export default config;

See Storybook SWC Configuration for more information

Other answered 12/6, 2024 at 21:39 Comment(0)
B
-1

I think what you need is path aliases. If you're working on a typescript project, you can declare aliases that map to a certain absolute path in your application using tsconfig.json paths compiler option:

"baseUrl": "./src",
"paths": {
  "components/*": ["components/*"],
  "@/common/*": ["common/*"],
 }

Be aware that is not always that easy because in production your build toolchain will have to translate them to the correct paths as tsc doesn’t do it. Fortunately nexjts has added this feature recently => https://nextjs.org/docs/advanced-features/module-path-aliases

Beebe answered 17/9, 2020 at 18:36 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.