React Styleguidist

Configuration

By default, Styleguidist will look for styleguide.config.js file in your project’s root folder. You can change the location of the config file using --config CLI option.

assetsDir

Type: String, optional

Your application static assets folder, will be accessible as / in the style guide dev server.

compilerConfig

Type: Object, default: { objectAssign: 'Object.assign' }

Styleguidist uses Bublé to run ES6 code on the frontend. This config object will be added as the second argument for buble.transform.

components

Type: String or Function, default: src/components/**/*.{js,jsx}

  • when String: a glob pattern that matches all your component modules.
  • when Function: a function that returns an array of module paths.

All paths are relative to config folder.

See examples in the Components section.

context

Type: Object, optional

Modules that will be available for examples. You can use it for utility functions like Lodash or for data fixtures.

module.exports = {
  context: {
    map: 'lodash/map',
    users: path.resolve(__dirname, 'fixtures/users')
  }
};

Then you can use them in any example:

<Message>{map(users, 'name').join(', ')}</Message>

contextDependencies

Type: String[], optional

Array of absolute paths that allow you to specify absolute paths of directories to watch for additions or removals of components.

By default Styleguidist uses common parent directory of your components.

module.exports = {
  contextDependencies: [
    path.resolve(__dirname, 'lib/components')
  ]
}

configureServer

Type: Function, optional

Function that allows you to add endpoints to the underlying Express server:

module.exports = {
  configureServer(app) {
     // `app` is the instance of the express server running Styleguidist
    app.get('/custom-endpoint', (req, res) => {
      res.status(200).send({ response: 'Server invoked' });
    });
  }
};

Your components will be able to invoke the URL http://localhost:6060/custom-endpoint from their examples.

dangerouslyUpdateWebpackConfig

Type: Function, optional

You may easily break Styleguidist using this options, try to use webpackConfig option instead.

Allows you to modify webpack config without any restrictions.

module.exports = {
  dangerouslyUpdateWebpackConfig(webpackConfig, env) {
    // WARNING: inspect Styleguidist Webpack config before modifying it, otherwise you may break Styleguidist
    console.log(webpackConfig);
    webpackConfig.externals = {
        jquery: 'jQuery'
    };
    return webpackConfig;
  }
};

defaultExample

Type: Boolean or String, default: false

For components that do not have an example, a default one can be used. When set to true, the DefaultExample.md is used, or you can provide the path to your own example Markdown file.

When writing your own default example file, __COMPONENT__ will be replaced by the actual component name at compile time.

getComponentPathLine

Type: Function, default: component file name

Function that returns a component path line (displayed under the component name).

For example, instead of components/Button/Button.js you can print import Button from 'components/Button';:

const path = require('path');
module.exports = {
  getComponentPathLine(componentPath) {
    const name = path.basename(componentPath, '.js');
    const dir = path.dirname(componentPath);
    return `import ${name} from '${dir}';`;
  }
};

getExampleFilename

Type: Function, default: finds Readme.md or ComponentName.md in the component folder

Function that returns examples file path for a given component path.

For example, instead of Readme.md you can use ComponentName.examples.md:

module.exports = {
  getExampleFilename(componentPath) {
    return componentPath.replace(/\.jsx?$/, '.examples.md');
  }
};

handlers

Type: Function, optional, default: [react-docgen-displayname-handler]

Function that returns functions used to process the discovered components and generate documentation objects. Default behaviors include discovering component documentation blocks, prop types, and defaults. If setting this property, it is best to build from the default react-docgen handler list, such as in the example below. See the react-docgen handler documentation for more information about handlers.

react-docgen-displayname-handler should be included.

module.exports = {
  handlers: componentPath => require('react-docgen').defaultHandlers.concat(
    (documentation, path) => {
      // Calculate a display name for components based upon the declared class name.
      if (path.value.type === 'ClassDeclaration' && path.value.id.type === 'Identifier') {
        documentation.set('displayName', path.value.id.name);

        // Calculate the key required to find the component in the module exports
        if (path.parentPath.value.type === 'ExportNamedDeclaration') {
          documentation.set('path', path.value.id.name);
        }
      }

      // The component is the default export
      if (path.parentPath.value.type === 'ExportDefaultDeclaration') {
        documentation.set('path', 'default');
      }
    },

    require('react-docgen-displayname-handler').createDisplayNameHandler(componentPath),
  )
};

highlightTheme

Type: String, default: base16-light

CodeMirror theme name to use for syntax highlighting in the editor.

ignore

Type: String[], default: ['**/__tests__/**', '**/*.test.js', '**/*.test.jsx', '**/*.spec.js', '**/*.spec.jsx']

Array of glob pattern that should not be included in the style guide.

You should pass glob patterns, for example, use **/components/Button.js instead of components/Button.js.

logger

Type: Object, by default will use console.* in CLI or nothing in Node.js API

Custom logger functions:

module.exports = {
	logger: {
    // One of: info, debug, warn
    // Suppress messages
		info: () => {},
    // Override display function
		warn: message => console.warn(`NOOOOOO: ${message}`),
	},
};

previewDelay

Type: Number, default: 500

Debounce time in milliseconds used before render the changes from the editor. While typing code the preview will not be updated.

propsParser

Type: Function, optional

Function that allows you to override the mechanism used to parse props from a source file. Default mechanism is using react-docgen to parse props.

module.exports = {
  propsParser(filePath, source, resolver, handlers) {
    return require('react-docgen').parse(source, resolver, handlers);
  }
};

require

Type: String[], optional

Modules that are required for your style guide. Useful for third-party styles or polyfills.

module.exports = {
  require: [
    'babel-polyfill',
    path.join(__dirname, 'styleguide/styles.css'),
  ]
};

This will add a separate webpack entry for each array item.

Don’t forget to add webpack loaders for each file you add here. For example, to require a CSS file you’ll need:

module.exports = {
  webpackConfig: {
    module: {
      rules: [
        {
          test: /\.css$/,
          use: [
            'style-loader',
            'css-loader'
          ]
        }
      ]
    }
  }
};

See Configuring webpack for mode details.

resolver

Type: Function, optional

Function that allows you to override the mechanism used to identify classes/components to analyze. Default behavior is to find all exported components in each file. You can configure it to find all components or use a custom detection method. See the react-docgen resolver documentation for more information about resolvers.

module.exports = {
  resolver: require('react-docgen').resolver.findAllComponentDefinitions
};

sections

Type: Array, optional

Allows components to be grouped into sections with a title and overview content. Sections can also be content only, with no associated components (for example, a textual introduction). Sections can be nested.

See examples of sections configuration.

serverHost

Type: String, default: 0.0.0.0

Dev server host name.

serverPort

Type: Number, default: 6060

Dev server port.

showCode

Type: Boolean, default: false

Show or hide example code initially. It can be toggled in the UI by clicking the Code button after each example.

showUsage

Type: Boolean, default: false

Show or hide props and methods documentation initially. It can be toggled in the UI by clicking the Props & methods button after each component description.

showSidebar

Type: Boolean, default: true

Toggle sidebar visibility. Sidebar will be hidden when opening components or examples in isolation mode even if this value is set to true. When set to false, sidebar will always be hidden.

skipComponentsWithoutExample

Type: Boolean, default: false

Ignore components that don’t have an example file (as determined by getExampleFilename). These components won’t be accessible from other examples unless you manually require them.

styleguideComponents

Type: Object, optional

Override React components used to render the style guide.

module.exports = {
	styleguideComponents: {
		Logo: path.join(__dirname, 'styleguide/components/Logo'),
		StyleGuideRenderer: path.join(__dirname, 'styleguide/components/StyleGuide'),
	},
};

See an example of customized style guide.

styleguideDir

Type: String, default: styleguide

Folder for static HTML style guide generated with styleguidist build command.

styles

Type: object, optional

Customize styles of any Styleguidist’s component.

See example in the cookbook.

template

Type: String, default: src/templates/index.html

HTML file to use as the template for the style guide. HTML webpack Plugin is used under the hood, see their docs for details.

theme

Type: object, optional

Customize style guide UI fonts, colors, etc.

See example in the cookbook.

title

Type: String, default: <app name from package.json> Style Guide

Style guide title.

updateExample

Type: Function, optional

Function that modifies code example (Markdown fenced code block). For example you can use it to load examples from files:

module.exports = {
  updateExample: function(props, exampleFilePath) {
    const { settings, lang } = props;
    if (typeof settings.file === 'string') {
      const filepath = path.resolve(exampleFilePath, settings.file);
      delete settings.file;
      return {
        content: fs.readFileSync(filepath),
        settings,
        lang,
      }
    }
    return props;
  }
};

Use it like this in your Markdown files:

```js { "file": "./some/file.js" }
```

You can also use this function to dynamically update some of your fenced code blocks that you do not want to be interpreted as React components by using the static modifier.

module.exports = {
  updateExample: function(props) {
    const { settings, lang } = props;
    if (lang === 'javascript' || lang === 'js' || lang === 'jsx') {
      settings.static = true;
    }
    return props;
  }
};

verbose

Type: Boolean, default: false

Print debug information. Same as --verbose command line switch.

webpackConfig

Type: Object or Function, optional

Custom webpack config options: loaders, extensions, plugins, etc. required for your project.

Can be an object:

module.exports = {
  webpackConfig: {
    module: {
      resolve: {
        extensions: ['.es6']
      },
      rules: [
        {
          test: /\.scss$/,
          loaders: ['style-loader', 'css-loader', 'sass-loader?precision=10']
        }
      ]
    }
  }
};

Or a function:

module.exports = {
  webpackConfig(env) {
    if (env === 'development') {
        return {
            // custom options
        };
    }
    return {};
  }
};

This option disables config load from webpack.config.js, load your config manually.

entry, externals, output, watch, and stats options will be ignored. For production builds, devtool will also be ignored.

CommonsChunkPlugins, HtmlWebpackPlugin, UglifyJsPlugin, HotModuleReplacementPlugin plugins will be ignored because Styleguidist already includes them or they may break Styleguidist.

Run style guide in verbose mode to see the actual webpack config used by Styleguidist: npm run styleguide -- --verbose.

See Configuring webpack for examples.