Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I use CSS framework styles inside a storybook #25

Closed
croogie opened this issue Apr 2, 2016 · 46 comments
Closed

How can I use CSS framework styles inside a storybook #25

croogie opened this issue Apr 2, 2016 · 46 comments

Comments

@croogie
Copy link

croogie commented Apr 2, 2016

Let's say that my application is basing on some CSS framework like Semantic UI, Bootstrap or something like that. How can I easily incorporate that styles inside a story book so that my components will display correctly?

@arunoda
Copy link
Member

arunoda commented Apr 2, 2016

Yes it is. Read here - https://github.com/kadirahq/react-storybook/blob/master/docs/setting-up-for-css.md

I that's not what you need, just reopen this.

UPD 2017-08-17 (@hypnos)
https://storybook.js.org/configurations/add-custom-head-tags/

@arunoda arunoda closed this as completed Apr 2, 2016
@andrioid
Copy link

Link is broken and I can't find it in the file in current master.

@arunoda
Copy link
Member

arunoda commented Oct 19, 2016

Check this: https://getstorybook.io/docs/configurations/custom-webpack-config

UPD 2017-08-17 (@hypnos)
https://storybook.js.org/configurations/custom-webpack-config/

@andrioid
Copy link

andrioid commented Oct 19, 2016

Thanks. An easier way was to add a head.html file in the ".storybook" directory with the elements for Bootstrap or Semantic UI

UPD 2017-08-17 (@hypnos)
Now it's preview_head.html

@wmhafiz
Copy link

wmhafiz commented Nov 14, 2016

Thanks head.html method works perfectly!

@felipecocco
Copy link

Would head.html also be the best way to go about it if the file for you are adding is not served through a URL but is instead hosted locally? how would that work?

ndelangen pushed a commit that referenced this issue Apr 5, 2017
ndelangen pushed a commit that referenced this issue Apr 5, 2017
Add storybook to devDependencies.
ndelangen pushed a commit that referenced this issue Apr 11, 2017
Write a storybook for components in this addon #25
ndelangen added a commit that referenced this issue Apr 11, 2017
@kirkstrobeck
Copy link

Both links are broken.

@ndelangen
Copy link
Member

Sorry for the broken links, this is unfortunately the result of our restructuring, The only way to find is by search.

What are you looking for / need help with @kirkstrobeck ? This issue is quite old and closed.
If you have a specific problem we can help you with, let us know 👍 .

@sergiotapia
Copy link

I landed here trying to figure out how to integrate React Storybook into a real application where all of our styles are in scss files in app/assets/stylesheets

@ndelangen
Copy link
Member

You'll need to extend our webpack config / provide your own custom webpack config.

In it you'll need to tell webpack what to do with the .scss-files. aka, you need to add the sass-loader.

Likely you already have this already setup for you app, and you can mostly copy-paste from it's webpack config?

@blairanderson
Copy link
Contributor

found in documentation: https://storybook.js.org/configurations/default-config/#css-support

@adamchenwei
Copy link

@arunoda would it possible remove above two links that have confused face I marked above? save time for others who enter this page in the future. Thanks!

@kirkstrobeck
Copy link

The confused reactions are probably enough. I upvoted em’ too.

@Hypnosphi
Copy link
Member

Just updated the comments with outdated links

@LukasMac
Copy link

Header file for story book is called preview-head.html Reference:
https://storybook.js.org/configurations/add-custom-head-tags/

@davidruisinger
Copy link

davidruisinger commented Nov 14, 2017

Within my "main" app my global styles are defined within a JS file that exports a template string containing all the global CSS rules.
Is there a way to add a template string with CSS definitions to the iframe where the stories are rendered in?

EDIT:
Since I’m using react-styled-components I’m now just using their injectGlobal helper.

@ndelangen
Copy link
Member

@flavordaaave I think you'll want to use just inject the styles in a style-tag from config.js

@davidruisinger
Copy link

@ndelangen So far all the possibilities of injecting global style (import './styles.css'; or via preview-head.html) don't allow me to inject styles with dynamic params.

My styles look something like this:

/* .storybook/config.js */

import theme from './theme'

export default `
html {
  font-family: Helvetica;
  background: ${theme.canvas_ground};
  ...
}
`

So for now I'm using the injectGlobal helper from react-styled-components as mentioned in my EDIT above.

/* .storybook/config.js */
...
import { injectGlobal } from 'styled-components'
import styles from '../src/styles'

injectGlobal`${styles}`
...

@Hypnosphi
Copy link
Member

Hypnosphi commented Nov 15, 2017

you can achieve a similar result with this:

// create a <style></style> DOM element
const styleElement = document.createElement('style')
// put the text from styles variable between opening and closing <style> tags
styleElement.appendChild(document.createTextNode(styles))
// place the style element inside <head>
document.head.appendChild(styleElement)

@bradfrost
Copy link

Hi there!
I'm trying to link up my stylesheet to Storybook, and am striking out.

I followed these instructions to import my CSS file (which lives in static/style.css in my project root) with this line: import '../static/style.css';. That resulted in an error with r

Error: Can't resolve '../i/link.svg' in [path]

I don't want to have to go through all this rigamarole to reconcile every externally-referenced resource in my stylesheet, so I thought I'd try a different way.

I added a preview-head.html per these docs, linking up my stylesheet like so:

<link rel="stylesheet" href="./static/style.css" />

This however results in a 404 error for the resource. I think it might just be a path issue, but can't seem to find which path I should be using relative to where Storybook is running. Any ideas?

@nickytonline
Copy link

If you're getting 404s because you're CSS is not on a CDN, you can pass an extra parameter to run Storybook with a static folder and reference your files as just ./some.css. Run storybook -p 9001 -s ./a-static-folder and put your css in that folder.

@bradfrost
Copy link

bradfrost commented Mar 29, 2018

Thanks for the suggestion, @nickytonline. Unfortunately that didn't seem to work. I have my files in static/style.css and I ran the command storybook -p 9001 -s ./static. That resulted in storybook: command not found. I ran npm run storybook -p 9001 -s ./static which ran, but still resulted in a 404 error on my stylesheet.

@nickytonline
Copy link

@bradfrost, just for clarification, when you run npm run storybook -p 9001 -s ./static, ./static acts like / in storybook, so if your file is in static/styles.css in your project, your link would be <link rel="stylesheet" href="./styles.css" /> not <link rel="stylesheet" href="./static/styles.css" />

@bradfrost
Copy link

bradfrost commented Mar 29, 2018

@nickytonline Yep, I had things linked up as <link rel="stylesheet" href="./styles.css" />.

@nickytonline
Copy link

nickytonline commented Apr 3, 2018

@bradfrost this was bugging me that it was not working for you so I create a very basic repo using create-react-app and the storybook CLI. It shows an example of a static asset being used in storybook being referenced via a <link /> tag. It's available here, https://github.com/nickytonline/for-brad

You can see the stylesheet being referenced here, https://github.com/nickytonline/for-brad/blob/master/.storybook/preview-head.html#L1

image

@bradfrost
Copy link

@nickytonline Thanks very much for the demo project! I really appreciate it.

The issue I'm still running into is reflected in my original post, which is the use of import to get the styles into the project. That method unfortunately throws errors if assets like fonts or icons or background images don't resolve. I realize there are ways of remedying that, but I guess I'm just looking to link up a stylesheet in the head of my document the ol' fashioned way.

@nickytonline
Copy link

nickytonline commented Apr 8, 2018

Sorry, my bad for not absorbing the entire content of your original post. That's quite the pickle if you want to avoid the rigamarole. Gonna have to think about that one a little bit.

@amos80m
Copy link

amos80m commented Jan 8, 2019

What you can do is to create a 'public' folder in the root folder.
in the 'public/semantic' folder pest the content of 'node_modules/semantic-ui-css'.
in package.json => scripts => storybook => add ''-s ./public"
last thing!!! in your component .less file do @import '/semantic/semantic.min.css';
now Icon should work smoothly.

@jmarceli
Copy link

jmarceli commented May 6, 2019

For Storybook v5 and normalize.css "framework" it is enough to just add import "normalize.css"; inside .storybook/config.js file.

@anton-paskanny
Copy link

@jmarceli It works for me, thanks a lot!

@snyderhaus
Copy link

Is this still a viable option with v6?

For Storybook v5 and normalize.css "framework" it is enough to just add import "normalize.css"; inside .storybook/config.js file.

@shilman
Copy link
Member

shilman commented Mar 31, 2020

@snyderhaus yes, though since 5.3 config.js has been soft-deprecated and we strongly suggest using preview.js instead. more info:

https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#to-mainjs-configuration

@scottc11
Copy link

scottc11 commented Apr 5, 2020

I have come to this thread numerous times for numerous projects! So this is for my own reference as well as anybody else.

This worked for me.

// storybook/config.js

import 'semantic-ui-css/semantic.min.css';
import 'bootstrap/dist/css/bootstrap.css';
import '!style-loader!css-loader!sass-loader!../client/scss/style.scss';

my style.scss is overriding the default bootstrap theme using sass variables

I was able to use storybooks default webpack config and just reference the style sheets like so, additionally using the inline loader syntax for my sass files, as shown in the docs.

"babel-core": "6.26.0",
"babel-loader": "7.1.4",
"@storybook/react": "^5.3.14",
"sass-loader": "^8.0.2",
"css-loader": "^3.4.2",
"style-loader": "0.20.3",
"react": "^16.3.2",

@gkortsit
Copy link

gkortsit commented Aug 12, 2020

For anyone using v6+ the solution using config.js will not work.

I've managed to make it work like so:

  • create a file named preview.js in the .storybook folder
  • import the external css. In my case they were scss files so I've imported them like this:
// .storybook/preview.js

import '!style-loader!css-loader!sass-loader!@company/framework/src/styles.sass'
import '!style-loader!css-loader!sass-loader!./cssoverrides.sass'

The second import was added to override some default global styles.

My folder structure:

.storybook
│   cssoverrides.sass
│   main.js  
│   preview.js

Packages used:

"@storybook/react": "^6.0.0",
"react": "^16.13.1",
"@babel/core": "^7.11.1",
"@babel/preset-env": "^7.11.0",
"@babel/preset-react": "^7.10.4",
"sass-loader": "^9.0.3",
"css-loader": "^4.2.1",
"style-loader": "^1.2.1"

@angelikipatrinou
Copy link

What worked for me was to import bootstrap on ./storybook/preview.js

//I added this:
import 'bootstrap-4-grid/css/grid.min.css';

//this was already there
export const parameters = {
  actions: { argTypesRegex: '^on[A-Z].*' },
};

https://storybook.js.org/docs/react/configure/styling-and-css#importing-css-files

@ArianZargaran
Copy link

In case you are injecting Bootstrap via CDN, a clean and easy solution is to populate Storybook Head Preview as mentioned in the docs: https://storybook.js.org/docs/react/configure/story-rendering#adding-to-head

This solution worked for me:

  • Create a new .storybook/preview-head.html file
  • Include any tag you may need in your Storybook iframe preview, HTML Head. In our case we are dropping Bootstraps CDN
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  • Launch your Storybook (re-build) and DONE!

@trickydisco78
Copy link

This was working when i was just importing global styles but now i've added a decorator to enable html preview the styles are no longer loaded

import { addDecorator } from '@storybook/html';
import { withHTMLDOC } from 'storybook-addon-html-document/html';

import '../src/css/styles.css';

addDecorator(withHTMLDOC);

@mleister97
Copy link

Storybook v6.+ solution

Super simple for everyone facing issues with importing custom styles/fonts/sass/...

Create a file called preview.js
Import your global stylesheet e.g.

preview.js

import "./../src/styles/index.scss";

@aboudard
Copy link

Storybook v6.+ solution

Super simple for everyone facing issues with importing custom styles/fonts/sass/...

Create a file called preview.js
Import your global stylesheet e.g.

preview.js

import "./../src/styles/index.scss";

Totally works, I have my custom bootstrap scss added to any .mdx doc file that I write.

@belloviniciusf
Copy link

Storybook v6.+ solution

Super simple for everyone facing issues with importing custom styles/fonts/sass/...

Create a file called preview.js
Import your global stylesheet e.g.

preview.js

import "./../src/styles/index.scss";

Recently we updated to v6 and had issues specifically on storybook, it resolved these, thanks.

@50l3r
Copy link

50l3r commented Sep 3, 2021

Storybook v6.+ solution

Super simple for everyone facing issues with importing custom styles/fonts/sass/...

Create a file called preview.js
Import your global stylesheet e.g.

preview.js

import "./../src/styles/index.scss";

If i try to do this it load styles well but overwrite storybook styles like code:

@import "buefy/src/scss/buefy.css"

I try to encapsulate with scss like this:

style.scss

#root>#buefy {
	& {
		@import "buefy/src/scss/buefy.css";
	}
}

preview.scss

import './style.scss'
export const decorators = [
	(story) => {
		return {
			components: { story },
			template: '<div id="buefy"><story /></div>',
		}
	},
]

But it ocurrs on reverse. Buttons style seems to big.

@drik98
Copy link
Contributor

drik98 commented Dec 23, 2021

I am currently having the same problems as @50l3r. (Just that we are using bootstrap instead of buefy.)

It should not be possible to overwrite the styling of the code section, the imported css should only apply to everything inside the .docs-story container.

@jdubs1994
Copy link

I am currently having the same problems as @50l3r. (Just that we are using bootstrap instead of buefy.)

It should not be possible to overwrite the styling of the code section, the imported css should only apply to everything inside the .docs-story container.

Did you ever figure out how to fix it?

Copy link
Member

shilman commented Nov 3, 2022

@jdubs1994 you can run your stories in iframes using the docs.iframeStories = true parameter. however, this has performance implications

@jdubs1994
Copy link

jdubs1994 commented Nov 3, 2022

@jdubs1994 you can run your stories in iframes using the docs.iframeStories = true parameter. however, this has performance implications

import '../src/scss/global.scss'

export const parameters = {
  actions: { argTypesRegex: "^on[A-Z].*" },
  docs: {
    iframeStories: true
  },
  controls: {
    matchers: {
      color: /(background|color)$/i,
      date: /Date$/,
    },
  },
}

Running into the same result, this is what my preview.js looks like. Everything looks good besides the code snippet section of the story.

@kerryj89
Copy link

kerryj89 commented Dec 28, 2023

It seems importing css through preview.js or via <link> attribute in preview-head.html or preview-body.html all yield the same unexpected result when using MDX (maybe for other curated formats, too?). That is, it treats the entire MDX container as a preview area (and not just limited to the canvas iframe of the stories within it). Check out the devtools for your imported css and you will see that not only is it loading the imported css for each individual story, but also the entire MDX area which should arguably NOT be the case (I think this area should be safeguarded from custom css imports unless iframe mode is set to inline).

For those of us with iframe mode enabled, I think we should have another depth of configurability that imports directly into the story canvas iframes (if we don't already have that option - I couldn't find it).

For now, I have to create a decorator to conditionally import the css I want and ONLY inside the story iframes. It discerns whether the iframe it's in is a story or not and conditionally loads in a link element pointing to the css.

// preview.js

export const decorators = [
  (story) => {
    const script = `
      <script>
        (function() {
          // Conditionally load the stylesheet
          if (document.location.search.startsWith('?viewMode=story')) {
            var link = document.createElement('link');
            link.rel = 'stylesheet';
            link.type = 'text/css';
            link.href = '/build/icp.css';
            document.head.appendChild(link);
          }
        })();
      </script>
    `;

    return `${script}
            ${story()}`;
  },
];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests