storybook cannot find module "example.png" in images loaded through css url() nextjs 13, tailwindcss
Asked Answered
U

2

5

i'm using nextjs 13, tailwindcss. trying to run storybook for the project would throw :

ModuleNotFoundError: Module not found: Error: Can't resolve '/images/example.png' in 'C:\repos\mvp\src\styles'

the cause is using bg-[url('/images/example.png')]

.storybook/main.ts

import type { StorybookConfig } from "@storybook/nextjs";
import path from 'path';
const config: StorybookConfig = {
  stories: ["../src/**/*.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/addon-interactions",
    'storybook-addon-next',
    {
      name: '@storybook/addon-styling',
      options: {
        // Check out https://github.com/storybookjs/addon-styling/blob/main/docs/api.md
        // For more details on this addon's options.
        postCss: true,
      },
    }
  ],
  framework: {
    name: "@storybook/nextjs",
    options: {},
  },
  docs: {
    autodocs: "tag",
  },
  webpackFinal:async(config, options)=> {
    config.resolve.alias = {
      ...config.resolve.alias,
      "@/components": path.resolve(__dirname, "../src/components"),
      "@/assets":path.resolve(__dirname, "../src/assets")
    };
    return config
  },
  staticDirs:[{from:"../public/images",to:"/images"}]
};
export default config;

terminal shows that "Serving static files from ./.\public\images at /images" is there a way to workaround this through storybook config without changing the value of css url() ?

Urrutia answered 24/4, 2023 at 12:59 Comment(0)
S
4

I had the same issue: my image was in the /public directory, at the root of my project. I could either make my app image work or make the storybook image work. The app import was url('/example.png') and the storybook import was url('/public/example.png').

To make an import that works for both apps, I used the ~ symbol in the URL path, which references the project root. So my working import is url('~public/example.png').

Also, don't forget to reference the staticDirs in the storybook config. In my case, it was staticDirs: ["../public"].

Siana answered 15/5, 2023 at 15:11 Comment(1)
thanks!, this is a valid way to work around the issue, but I wanted to find a solution where I can use storybook without changing my Nextjs syntaxUrrutia
B
2

Add "/images":path.resolve(__dirname, "../src/assets/images") to your config.resolve.alias.

Bolt answered 25/8, 2023 at 21:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.