I am setting up UI Storybooks with its newer version of 8.1.4
but could not get the style-loader and css-loader to work in a compatible way such that CSS modules can be properly loaded into the canvas of the Storybook server page.
My UI component PageHeader.tsx
loads the CSS module as below:
import styles from './PageHeader.module.scss';
The ./PageHeader.module.scss
module contains:
.headerContainer {
display: flex;
flex-direction: column;
}
Once I start the storybook server, I get below exception message.
TypeError: Cannot read properties of undefined (reading 'headerContainer')
at PageHeader (http://localhost:6006/PageHeader-PageHeader-stories.iframe.bundle.js:587:89)
...
This indicates the styles
object is undefined
, meaning either of the loaders could not recognize that default import statement properly.
If I change the statement to import * as styles from './PageHeader.module.scss';
, everything started working. But I have many UI components. I do not wish to change their syntax for the sole purpose of supporting storybooks.
The style sheet loading rule of the Webpack config in main.ts
of Storybook configuration reads like below.
config.module.rules.push({
test: /.scss$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: {
mode: 'local',
localIdentName: '[path][name]__[local]_[hash:base64:5]',
},
importLoaders: 1,
}
},
'sass-loader'
],
And in pakcage.json
, the versions of the related pakcages are:
"@storybook/addon-actions": "^8.1.4",
"@storybook/addon-essentials": "^8.1.4",
"@storybook/addon-interactions": "^8.1.4",
"@storybook/addon-links": "^8.1.4",
"@storybook/addon-webpack5-compiler-swc": "^1.0.3",
"@storybook/blocks": "^8.1.4",
"@storybook/react": "^8.1.4",
"@storybook/react-webpack5": "^8.1.4",
"@storybook/server-webpack5": "^8.1.4",
"@storybook/test": "^8.1.4",
"css-loader": "^7.1.2",
"sass": "^1.77.0",
"sass-loader": "^14.2.1",
"style-loader": "^4.0.0",
"webpack": "^5.91.0"
I have to admit that Webpack is a beast to work out on getting the right loaders for styling sheets and JavaScript/TypeScript source code. Storybooks bring that complexity to a higher level with its aggressive breaking changes across versions.