CRA + TypeScript での storybook の設定

create-react-app で TypeScriptをサポートしているのいいんだけど、その時のstorybookの設定がよく分からなかった。

バーション

  • react-scripts@2.1.0
  • typescript@3.1.6
  • @storybook/react@4.0.0

Storybookの公式に色々書いてあって、 awesome-typescript-loaderとかを書いてある通りに設定したら動きはしたんだけど、 結局create-react-app本体の設定コード読んだほうがビルドしたものと一緒の設定になっていいかなと思い次のようにしてみました。

const TSDocgenPlugin = require('react-docgen-typescript-webpack-plugin');

module.exports = (baseConfig, env, config) => {
  config.module.rules.push(
    {
      test: /\.mjs$/,
      include: /node_modules/,
      type: 'javascript/auto',
    },
    {
      test: /\.(ts|tsx)$/,
      use: [
        {
          loader: 'babel-loader',
          options: {
            presets: ['react-app'],
          },
        },
      ],
    },
  );
  config.plugins.push(new TSDocgenPlugin());
  config.resolve.extensions.push('.mjs', '.ts', '.tsx');

  return config;
};

結果として設定も簡単になったと思います。 .mjsの設定はCan't reexport the named export '....' from non EcmaScript module というエラーへの対応です。

こういう風にあからさまに babel-preset-react-app に依存した時、devDependenciesに足したくなるけどJavaScriptの場合どうするのがいいんだろう? react-scripts内部の依存を直接使うのは良くない気がするけど、足しちゃうとreact-scriptsだけバージョンあげてバージョンが合わなくなったりしそう。