Is there a way to incorporate static assets in SCSS while using Storybook?

I've created a SCSS library located in the styles/ folder with code like this:

// Variables
$path-to-img: "/img" !default;
$path-to-fonts: "/fonts" !default;

// Example use case
.bg-pattern-2 {
  background-image: linear-gradient(to bottom, transparent 0%, $black 100%), url('#{$path-to-img}/patterns/pattern-2.png');
}

In my Next.js project, all static assets are stored in the public/ folder structure:

public/
------- img/
------- fonts/
------- ...
       

However, when attempting to run start-storybook -p 9000, an error is thrown:

https://i.stack.imgur.com/Zs6xC.png

The error is expected, but how can it be resolved effectively?

Perhaps utilizing webpack for a solution?

Answer №1

Success! I finally cracked the code.

To begin with, a quick peek at the Webpack configuration structure can be achieved by running yarn storybook --debug-webpack.

Upon thorough investigation, it became evident that the publicPath was set to "", indicating that assets needed to reside in the .storybook directory under subfolders /img and /fonts.

But why?

This is because the html output rendering the Storybook app shares the same path as injected CSS files, one of which originates from the sass-loader.

The remedy:

  webpackFinal: async (config, { configType }) => {
    // Integrate Sass into Storybook
    config.module.rules.push({
      test: /\.scss$/,
      include: path.resolve(__dirname, "../styles"),
      use: [
        {
          loader: "style-loader",
        },
        {
          loader: "css-loader",
          options: {
            url: false, // Crucial flag ** refer explanation
          },
        },
        {
          loader: "sass-loader",
        },
      ],
    });

    // Transfer all assets to publicPath
    config.plugins.push(
      new CopyPlugin({
        patterns: [
          {
            from: path.resolve(__dirname, "../public/fonts"),
            to: "./fonts", 
          },
          {
            from: path.resolve(__dirname, "../public/img"),
            to: "./img", 
          },
        ],
      })
    );

    return config;
  },

options {url: false} This setting resolved my predicament. Essentially, when utilizing:

// Illustrative example
.bg-pattern-2 {
  background-image: linear-gradient(to bottom, transparent 0%, $black 100%), url('#{$path-to-img}/patterns/pattern-2.png');
}

the css-loader generates its own URLs, causing mismatches in image paths within the injected CSS.

By deactivating this feature, we can then relocate these assets using the copy-webpack-plugin to the publicPath of webpack, enabling everything to function seamlessly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When ts-loader is used to import .json files, the declaration files are outputted into a separate

I've encountered a peculiar issue with my ts-loader. When I import a *.json file from node_modules, the declaration files are being generated in a subfolder within dist/ instead of directly in the dist/ folder as expected. Here is the structure of my ...

Rendering with Next.js script

Within my Next.js project, there is a script implemented to render a widget. The code for this script looks like: <a className="e-widget no-button xdga generic-loader" href="https://example" rel="no ...

Is Next.js the Ultimate Serverless Rendering Tool with Cloudflare Workers?

I am currently using Next.js version 9 and I am interested in utilizing Next's serverless deployment feature by integrating my application with Cloudflare Workers. According to the documentation for Next.js, all serverless functions created by Next f ...

What is the reason behind the mandatory credentials option for the CredentialsProvider?

When using NextAuth.js with a custom sign in page, some code examples for the credentials provider do not include the credentials option in the CredentialsProvider. According to the documentation (here), the credentials option is meant to automatically "ge ...

Using numerous named parameters in package.json script argument

I currently have a webpack configuration with three parameters that function properly when invoked like this: webpack --env.p1 = "p1_value" --env.p2 = "p2_value" --env.p3 = "p3_value" Now I aim to consolidate that webpack command within the following pac ...

Is there a way to resolve the issue with sequelize not running 'npx sequelize-cli db:migrate' command through docker-compose.yml?

Currently encountering the following issue: Sequelize CLI [Node: 21.7.1, CLI: 6.6.2, ORM: 6.37.1] | | Loaded configuration file "database/config/config.json". | Using environment "production". | ERROR: Access denied for user 'root ...

Creating a Modal using Typescript with NextJS

Currently, I'm working on creating a modal within my app using NextJS with Typescript. Unfortunately, I've been struggling to eliminate the warning associated with my modal selector. Can someone provide guidance on how to properly type this? cons ...

Navigating through pages in a server component using Next.js

I am currently working on a project that involves implementing pagination using the NextJS 13 server component without relying on the use client. The goal is to ensure that when a button is clicked, new entries are added to the screen in a sequential order ...

What is the best way to transfer user input data from a Form component to the state of its parent component in react hooks before submitting?

Currently, I am in the process of setting up a multi-step form for facilitating sign-ins using Next.js and Material-UI. The core functionality of the multi-step form is implemented within the signup.js page located at pages/signup.js. I have created child ...

Can webpack effectively operate in both the frontend and backend environments?

According to the information provided on their website, packaging is defined as: webpack serves as a module bundler with its main purpose being to bundle JavaScript files for usage in a browser. Additionally, it has the ability to transform, bundle, or ...

Configuring webpack in Next.js can be done through the `next.config.js` file

I am currently utilizing NextJS and incorporating the react-data-export plugin for generating xls files. The description of the plugin mentions: This particular library makes use of file-saver and xlsx, and by integrating json-loader, the desired functio ...

"Encountering issues with DefinePlugin when using the combination of Ionic, Angular, Webpack,

I'm trying to incorporate my process.env variable into the webpack Bundle using DefinePlugin. Here's the snippet of code in my webpack config: plugins: [ new webpack.DefinePlugin({ 'process.env': JSON.stringify(process.env) ...

Is there a way to access and parse a CSV file from a URL within a Next.js project?

Currently working on a Next.js application available here. The task at hand requires reading a CSV file from a specific URL within the same repository in multiple instances. Unfortunately, I am encountering difficulties retrieving this data. You can locate ...

I am not seeing anything when I ask for a second perspective

My tech stack includes Ruby on Rails as the framework and Vue.js for data display. I'm using Axios for API requests. To start a project, I used the following command: rails new myapp --webpack=vue This created a folder structure in Rails: app/java ...

Getting rid of a cookie from the header in Reactjs

Currently, I'm developing an application with Reactjs and utilizing the Next.js framework. To manage user authentication, I've implemented cookies. However, I am facing a challenge when it comes to logging out users and removing the cookie. Could ...

Issue with getStaticProps in Next.js component not functioning as expected

I have a component that I imported and used on a page, but I'm encountering the error - TypeError: Cannot read property 'labels' of undefined. The issue seems to be with how I pass the data and options to ChartCard because they are underline ...

What is the process for accessing and interpreting request body and query parameters in the next 13 API using the app router in the route.ts file?

I couldn't find a solution on this page: https://nextjs.org/docs/app/api-reference/file-conventions/route. ...

Unlocking the power of canonical URLs in Next.js with Automatic Static Optimization enabled

I am currently developing an SEO component that requires a canonical URL. Is there a way to obtain the URL of a static page in Next.js when Automatic Static Optimization is enabled? ...

What steps can be taken to extend the request/response timeout in AWS Amplify?

Currently, my NextJS frontend is hosted on AWS Amplify and I'm encountering a 504 Gateway Timeout Error after a short period of time. The backend API, hosted separately in ECS, is running slow causing this issue. I am curious to know what the default ...

Step-by-step guide: Logging into next js with auth0

Having trouble logging in to a Next.js app with Auth0? I followed the quickstart guide on the Auth0 website, but I'm encountering an error on the login page. <a href="/api/auth/login">Login</a> This is pages/api/[...auth0].js i ...