What is the best way to set up Storybook.js Webpack to support absolute image paths within CSS modules for a Next.js project?

I'm currently setting up Storybook to integrate with Next.js, Ant Design, Less, and TypeScript. In Next.js, images need to be stored in the public/ directory and linked using absolute paths for universal usage within the project. I am facing challenges in configuring the webpack of Storybook.js to resolve these absolute image paths.

For instance, within a CSS module:

.testImage {
  background-image: url('/images/cucumber.png');
  background-repeat: no-repeat;
  background-size: contain;
  height: 300px;
  width: 300px;
}

However, Storybook encounters an error during build:

ERROR in ./common/layout/TestImage/TestImage.module.css (./node_modules/css-loader/dist/cjs.js??ref--15-1!./common/layout/TestImage/TestImage.module.css)
Module build failed (from ./node_modules/css-loader/dist/cjs.js):
Error: Can't resolve '/images/cucumber.png' in '/Users/gerritvanderlugt/Development/misc/storybook-issue/common/layout/TestImage'
    ... [error details]
    at /Users/gerritvanderlugt/Development/misc/storybook-issue/node_modules/enhanced-resolve/lib/Resolver.js:285:5
 @ ./common/layout/TestImage/TestImage.module.css 2:12-115 9:17-24 13:7-14 45:20-27 47:4-60:5 49:6-59:7 50:38-45 56:26-33 58:21-28 68:15-22
 ... [more errors follow] ...

I've experimented with file-loader, url-loader, and css-loader without success. Any assistance on this matter would be highly appreciated!

Here's the GitHub repository where you can reproduce the issue by executing npm install followed by npm run storybook.

Answer №1

Essentially, you've already set up an image loader in your application which allows you to load images. The problem lies in the fact that the css-loader does not resolve absolute paths like /images/cucumber.png (it only supports relative paths). To solve this issue, you can manually resolve it by doing the following:

newConfig.resolve.alias['/images/cucumber.png'] = path.resolve(__dirname, '../public/images/cucumber.png');

return newConfig;

Answer №2

Inspired by @tmhao2005's response, I took the initiative to craft my own .storybook/webpack.config.js using the following code snippet:

const path = require('path')

module.exports = ({ configuration }) => {
  configuration.resolve.alias['/assets/some-image.jpg'] = path.resolve(
    __dirname,
    '../public/assets/some-image.jpg',
  )

  return configuration
}

Answer №3

To set up a static directory specifically for Storybook, you can include the following line in your run script:

"start-storybook": "start-storybook -s ./storybook-assets -p 9001"

Answer №4

After encountering a similar problem, I managed to resolve it using the following solution.

// storybook/main.js

module.exports = {
  staticDirs: ['../public']
};

Learn more about Serving static files via Storybook Configuration here

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

I added an onClick event to an SVG image, however, I am struggling to get the event to execute a jQuery if/else statement

I've been working on creating an SVG map of the US, and I'm almost finished. The final step involves implementing a simple if-else statement to prompt users for the name of the state when they click on it. My goal is to fill the state green if th ...

Formatting code within an HTML document

I am attempting to customize a stock widget that I obtained from financialcontent.com. My current approach involves using Bootstrap for styling purposes. To incorporate the widget into a div, I found it necessary to embed the script directly within the HT ...

Unable to capture mistakes in function executed within try-catch statement

I'm currently facing challenges with implementing asynchronous functions in a Node.js server. This is my first experience working with try/catch blocks and I'm strugging to catch errors within the called function. Here's an excerpt of my co ...

Is there a way to use an Angular $watch to determine the specific changes made to $scope.value?

I am monitoring a variable called $scope.value with a watch in my code. There are two ways in which the value can be updated: The first is by updating it from the controller, such as through any services. The second way is that any input event can also ...

Exploring the DOM in JavaScript: Searching for the final ancestor containing a specific attribute

Check out this example of HTML code: <div id="main1" data-attribute="main"> <div id="section2" data-attribute="subsection"> <div id="nested3" data-attribute="sub-subsection"> </div> </div> </div> <div id= ...

Tips for eliminating unnecessary or duplicate dependencies in package.json files

While I am aware that this question has been asked previously on Stack Overflow, I have found that depcheck does not work effectively for me. It provides numerous false alerts and requires specific configuration for libraries like babel, eslint, etc. How ...

Check two arrays by comparing the first array and return the values that have a partial match, even if they are not

Hi there, I'm trying to filter my array based on another array, even if the values don't match exactly. Here is an example of what I'm working with: First array: [Mon Sep 09 2019 00:00:00 GMT+1000 (Australian Eastern Standard Time), Tue Sep ...

Comparing JSON files in JavaScript to identify and extract only the new objects

I need a way to identify and output the newly added objects from two JSON files based on their "Id" values. It's important for me to disregard changes in object positions within the files and also ignore specific key-value changes, like Greg's ag ...

Removing dropdown lists from input forms can be achieved without using jQuery by utilizing vanilla JavaScript

Looking to build a custom HTML/JavaScript terminal or shell. Interested in utilizing an input box and form to interact with JavaScript functions/commands. Unsure of how to eliminate the drop-down menu that appears after previous inputs. Pictured terminal: ...

Having trouble applying styles to a component using forwardRef

I'm relatively new to React and still trying to wrap my head around the component's lifecycle. However, the issue at hand is proving to be quite perplexing. One thing that confuses me is why adding "setState(10);" causes the style of the "Test" ...

Which RxJS operators necessitate unsubscription?

It can be confusing to know which operators in RxJS must be unsubscribed from to prevent subscription leaks. Some, like forkJoin, complete automatically, while others, such as combineLatest, never complete. Is there a comprehensive list or guideline availa ...

Can someone help me figure out the issue with my Angularjs ng-repeat implementation?

After spending hours trying to figure out why something so simple is not working, I'm at a loss. Testing with a dummy list proves the functionality works, but when I connect my server-side data source, it fails. The JSON returned from the AJAX call i ...

Understanding Aspect Ratios in CSS for Div Containers and their Components

I am crafting an HTML5 game without the use of canvas and aiming to maintain a 16:9 aspect ratio within my div. Thanks to javascript, achieving this is straightforward and it functions flawlessly. However, the elements inside the div occasionally appear to ...

Troubleshooting the issue of React forms hook not functioning properly with Material UI Select input

How the Textfield below should load: https://i.sstatic.net/29Sz4.png How it actually loads: https://i.sstatic.net/TdPYM.png My Select component, created using Material UI and React form hook, is not loading the default value as expected. The component ...

Issue: Unable to locate module - Error in integration of Vue.js with Laravel framework

I'm currently following a tutorial on YouTube for setting up Vue and Laravel. My resources folder structure looks like this so far: - resources - js - app.js - vue -app.vue In my app.js file: require('./bootstrap&ap ...

Converting JSON array with ES6 functions

I have a specific array format that needs to undergo transformation. { [ { "condition": "$and", "children": [ { "column": "Title", "comparison": "$eq", "columnValue& ...

Guide on changing the background image of an active thumbnail in an autosliding carousel

My query consists of three parts. Any assistance in solving this JS problem would be highly appreciated as I am learning and understanding JS through trial and error. https://i.sstatic.net/0Liqi.jpg I have designed a visually appealing travel landing pag ...

What is the best way to execute a function in Meteor while ensuring it responds reactively

There is a function in my code that handles gui-logic, and I want it to be executed every time a template is updated reactively in Meteor. I attempted to place the code within the Template.myTemplate.helpers section as shown below, but it caused everythin ...

Node.js server experiences a crash after attempting to send a large string using res.send()

I've recently started learning JavaScript and NodeJs. I'm facing an issue with my Nodejs application crashing when a get request is made, specifically when trying to return a large string. app.mjs app.get('/log', function (req, res) { ...

Instructions for incorporating highcharts sub modules into a React application

I have been utilizing the react-jsx-highcharts library to seamlessly integrate Highcharts into my React application. Everything is functioning perfectly. However, I am now interested in incorporating the boost module. I attempted to add it by simply using ...