Serving Static Files

It’s often useful to load static files like images and videos when creating components and stories.

Storybook provides two ways to do that.

1. Via Imports

You can import any media assets by simply importing (or requiring) them as shown below.

  1. import React from 'react';
  2. import { storiesOf } from '@storybook/react';
  3. import imageFile from './static/image.png';
  4. const image = {
  5. src: imageFile,
  6. alt: 'my image',
  7. };
  8. storiesOf('<img />', module)
  9. .add('with an image', () => (
  10. <img src={image.src} alt={image.alt} />
  11. ));

This is enabled with our default config. But, if you are using a custom Webpack config, you need to add the file-loader into your custom Webpack config.

2. Via a Directory

You can also configure a directory (or a list of directories) for searching static content when you are starting Storybook. You can do that with the -s flag.

See the following npm script on how to use it:

  1. {
  2. "scripts": {
  3. "start-storybook": "start-storybook -s ./public -p 9001"
  4. }
  5. }

Here ./public is our static directory. Now you can use static files in the public directory in your components or stories like this.

  1. import React from 'react';
  2. import { storiesOf } from '@storybook/react';
  3. const imageAlt = 'my image';
  4. // assume image.png is located in the "public" directory.
  5. storiesOf('<img />', module)
  6. .add('with a image', () => (
  7. <img src="/image.png" alt={imageAlt} />
  8. ));

You can also pass a list of directories separated by commas without spaces instead of a single directory.

  1. {"scripts": { "start-storybook": "start-storybook -s ./public,./static -p 9001"}}

3. Via a CDN

Upload your files to an online CDN and just reference them.In this example we’re using a placeholder image service.

  1. import React from 'react';
  2. import { storiesOf } from '@storybook/react';
  3. storiesOf('<img />', module)
  4. .add('with a image', () => (
  5. <img src="https://placehold.it/350x150" alt="My CDN placeholder" />
  6. ));

Absolute versus relative paths

Sometimes, you may want to deploy your storybook into a subpath, like https://example.com/storybook.

In this case, you need to have all your images and media files with relative paths. Otherwise, Storybook cannot locate those files.

If you load static content via importing, this is automatic and you do not have to do anything.

If you are using a static directory, then you need to use relative paths to load images.