TypeScript Config

This is a central reference for using Storybook with TypeScript.

Setting up TypeScript with awesome-typescript-loader

Dependencies you may need

  1. yarn add -D typescript
  2. yarn add -D awesome-typescript-loader
  3. yarn add -D @types/storybook__react # typings
  4. yarn add -D @storybook/addon-info react-docgen-typescript-loader # optional but recommended
  5. yarn add -D jest "@types/jest" ts-jest #testing

We have had the best experience using awesome-typescript-loader, but other tutorials may use ts-loader, just configure accordingly. You can even use babel-loader with a ts-loader configuration.

Setting up TypeScript to work with Storybook

We first have to use the custom Webpack config in full control mode, extending default configs by creating a webpack.config.js file in our Storybook configuration directory (by default, it’s .storybook):

  1. module.exports = ({ config }) => {
  2. config.module.rules.push({
  3. test: /\.(ts|tsx)$/,
  4. use: [
  5. {
  6. loader: require.resolve('awesome-typescript-loader'),
  7. },
  8. // Optional
  9. {
  10. loader: require.resolve('react-docgen-typescript-loader'),
  11. },
  12. ],
  13. });
  14. config.resolve.extensions.push('.ts', '.tsx');
  15. return config;
  16. };

The above example shows a working Webpack config with the TSDocgen plugin integrated. This plugin is not necessary to use Storybook and the section marked // optional can be safely removed if the features of TSDocgen are not required.

tsconfig.json

  1. {
  2. "compilerOptions": {
  3. "outDir": "build/lib",
  4. "module": "commonjs",
  5. "target": "es5",
  6. "lib": ["es5", "es6", "es7", "es2017", "dom"],
  7. "sourceMap": true,
  8. "allowJs": false,
  9. "jsx": "react",
  10. "moduleResolution": "node",
  11. "rootDirs": ["src", "stories"],
  12. "baseUrl": "src",
  13. "forceConsistentCasingInFileNames": true,
  14. "noImplicitReturns": true,
  15. "noImplicitThis": true,
  16. "noImplicitAny": true,
  17. "strictNullChecks": true,
  18. "suppressImplicitAnyIndexErrors": true,
  19. "noUnusedLocals": true,
  20. "declaration": true,
  21. "allowSyntheticDefaultImports": true,
  22. "experimentalDecorators": true,
  23. "emitDecoratorMetadata": true
  24. },
  25. "include": ["src/**/*"],
  26. "exclude": ["node_modules", "build", "scripts"]
  27. }

This is for the default configuration where /stories is a peer of src. If you have them all in just src you may wish to replace "rootDirs": ["src", "stories"] above with "rootDir": "src",.

Setting up TypeScript with babel-loader

When using latest create-react-app (CRA 2.0), Babel 7 has native TypeScript support. Setup becomes easier.For a full working demo (that also uses react-docgen-typescript-loader) you can check out this repo.

Dependencies you may need

  1. yarn add -D @types/storybook__react # typings

Setting up TypeScript to work with Storybook

We first have to use the custom Webpack config in full control mode, extending default configs by creating a webpack.config.js file in our Storybook configuration directory (by default, it’s .storybook):

  1. module.exports = ({ config, mode }) => {
  2. config.module.rules.push({
  3. test: /\.(ts|tsx)$/,
  4. loader: require.resolve('babel-loader'),
  5. options: {
  6. presets: [['react-app', { flow: false, typescript: true }]],
  7. },
  8. });
  9. config.resolve.extensions.push('.ts', '.tsx');
  10. return config;
  11. };

tsconfig.json

The default tsconfig.json that comes with CRA works great. If your stories are outside the src folder, for example the stories folder in root, then "rootDirs": ["src", "stories"] needs to be added to be added to compilerOptions so it knows what folders to compile. Make sure jsx is set to preserve. Should be unchanged.

Create a TSX storybook index

The default storybook index file is stories/index.stories.js — you’ll want to rename this to stories/index.stories.tsx.

Import tsx stories

Change config.ts inside the Storybook config directory (by default, it’s .storybook) to import stories made with TypeScript:

  1. import { configure } from '@storybook/react';
  2. // automatically import all files ending in *.stories.tsx
  3. const req = require.context('../stories', true, /\.stories\.tsx$/);
  4. function loadStories() {
  5. req.keys().forEach(req);
  6. }
  7. configure(loadStories, module);

Using TypeScript with the TSDocgen addon

The very handy Storybook Info addon autogenerates prop tables documentation for each component, however it doesn’t work with Typescript types. The current solution is to use react-docgen-typescript-loader to preprocess the TypeScript files to give the Info addon what it needs. The webpack config above does this, and so for the rest of your stories you use it as per normal:

  1. import * as React from 'react';
  2. import { storiesOf } from '@storybook/react';
  3. import { action } from '@storybook/addon-actions';
  4. import TicTacToeCell from './TicTacToeCell';
  5. const stories = storiesOf('Components', module);
  6. stories.add(
  7. 'TicTacToeCell',
  8. () => <TicTacToeCell value="X" position={{ x: 0, y: 0 }} onClick={action('onClick')} />,
  9. { info: { inline: true } }
  10. );

Customizing Type annotations/descriptions

Please refer to the react-docgen-typescript-loader docs for writing prop descriptions and other annotations to your Typescript interfaces.

Additional annotation can be achieved by setting a default set of info parameters:

  1. import { addDecorator } from '@storybook/react';
  2. import { withInfo } from '@storybook/addon-info';
  3. // Globally in your .storybook/config.js, or alternatively, per-chapter
  4. addDecorator(
  5. withInfo({
  6. styles: {
  7. header: {
  8. h1: {
  9. marginRight: '20px',
  10. fontSize: '25px',
  11. display: 'inline',
  12. },
  13. body: {
  14. paddingTop: 0,
  15. paddingBottom: 0,
  16. },
  17. h2: {
  18. display: 'inline',
  19. color: '#999',
  20. },
  21. },
  22. infoBody: {
  23. backgroundColor: '#eee',
  24. padding: '0px 5px',
  25. lineHeight: '2',
  26. },
  27. },
  28. inline: true,
  29. source: false,
  30. })
  31. );

This can be used like so:

  1. import * as React from 'react';
  2. import { storiesOf } from '@storybook/react';
  3. import { PrimaryButton } from './Button';
  4. import { text, select, boolean } from '@storybook/addon-knobs/react';
  5. storiesOf('Components/Button', module).addWithJSX(
  6. 'basic PrimaryButton',
  7. () => (
  8. <PrimaryButton
  9. label={text('label', 'Enroll')}
  10. disabled={boolean('disabled', false)}
  11. onClick={() => alert('hello there')}
  12. />
  13. ),
  14. {
  15. info: {
  16. text: `
  17. ### Notes
  18. light button seen on <https://zpl.io/aM49ZBd>
  19. ### Usage
  20. ~~~js
  21. <PrimaryButton
  22. label={text('label', 'Enroll')}
  23. disabled={boolean('disabled',false)}
  24. onClick={() => alert('hello there')}
  25. />
  26. ~~~
  27. `,
  28. },
  29. }
  30. );

And this is how it looks:

image

Note: Component docgen information can not be generated for components that are only exported as default. You can work around the issue by exporting the component using a named export.

Setting up Jest tests

The ts-jest README explains pretty clearly how to get Jest to recognize TypeScript code.

This is an example jest.config.js file for jest:

  1. module.exports = {
  2. transform: {
  3. '.(ts|tsx)': 'ts-jest',
  4. },
  5. testPathIgnorePatterns: ['/node_modules/', '/lib/'],
  6. testRegex: '(/test/.*|\\.(test|spec))\\.(ts|tsx|js)$',
  7. moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
  8. };

Building your TypeScript Storybook

You will need to set up some scripts - these may help:

  1. "scripts": {
  2. "start": "react-scripts-ts start",
  3. "build": "npm run lint && npm run build-lib && build-storybook",
  4. "build-lib-watch": "tsc -w",
  5. "build-lib": "tsc && npm run copy-css-to-lib && npm run copy-svg-to-lib && npm run copy-png-to-lib && npm run copy-woff2-to-lib",
  6. "test": "react-scripts-ts test --env=jsdom",
  7. "test:coverage": "npm test -- --coverage",
  8. "eject": "react-scripts-ts eject",
  9. "storybook": "start-storybook -p 6006",
  10. "build-storybook": "build-storybook",
  11. "copy-css-to-lib": "cpx \"./src/**/*.css\" ./build/lib",
  12. "copy-woff2-to-lib": "cpx \"./src/**/*.woff2\" ./build/lib",
  13. "copy-svg-to-lib": "cpx \"./src/**/*.svg\" ./build/lib",
  14. "copy-png-to-lib": "cpx \"./src/**/*.png\" ./build/lib",
  15. "lint": "tslint -c tslint.json 'src/**/*.{ts,tsx}'"
  16. },