webpack 4系、ts-loader 4系、storybook 4系にしたときに出る謎のエラーを解決
React で storybook を使ってコンポーネントベースのUI開発をするっていうのが、こんな書籍も出てるぐらい
Atomic Design ~堅牢で使いやすいUIを効率良く設計する
- 作者: 五藤佑典
- 出版社/メーカー: 技術評論社
- 発売日: 2018/04/25
- メディア: 単行本(ソフトカバー)
- この商品を含むブログ (1件) を見る
今フロントエンド界隈では熱いみたいなので、挑戦してみたのですが、出鼻を盛大にくじかれたエラーの解決方法を盛大に記しておきたい。
webpackの設定はつらい。
TypeScriptのコンパイルは通るが、storybook が動かない
まず最新の webpack 4系、ts-loader 4系、@storybook/react 4系にすると、TypeScriptのコンパイルは通るが、storybook が動かない
Module build failed: TypeError: Cannot set property 'tsLoaderDefinitionFileVersions' of undefined
もしくは、
Module build failed: TypeError: Cannot read property 'afterCompile' of undefined
あたりのエラーというかワーニングが出てコンパイルできないので、ググってみると ts-loader のバージョンを 3.5.0 に下げろ、というギフハブイシューなどが見つかる。
stotybook は動いたが、TypeScript がコンパイルできない
しょうがなしに、ts-loader を 3.5.0 に下げて動かしてみる。なるほど、 stotybook は確かに動いた。が、今後は TypeScript がコンパイルできない。
さらに調べると、ts-loader はまぁ、4系でいいから、@storybook/react の方を 4.0.0-alpha.10 にあげてみろという話が見つかる。 すると、なんかまたよくわからないエラーが出たので、
このあたりの、公式ドキュメントを眺めつつ、
- https://storybook.js.org/configurations/custom-webpack-config/
- https://storybook.js.org/configurations/typescript-config/
.storybook 以下の webpack.config.js やら、config.js の設定を見直す。
webpack.config.js の方は、path とか TypeScript 使ってたら ts-loader とかを設定する(react-docgen-typescript-webpack-plugin が一体なんなのかは今は放置)。
const path = require("path"); const TSDocgenPlugin = require("react-docgen-typescript-webpack-plugin"); module.exports = (baseConfig, env, defaultConfig) => { defaultConfig.module.rules.push({ test: /\.(ts|tsx)$/, include: path.resolve(__dirname, "../src"), loader: require.resolve("ts-loader") }); defaultConfig.plugins.push(new TSDocgenPlugin()); // optional defaultConfig.resolve.extensions.push(".ts", ".tsx"); return defaultConfig; };
config.js は
import { configure } from '@storybook/react'; // automatically import all files ending in *.story.tsx const req = require.context('../src/stories', true, /.story.tsx$/); function loadStories() { req.keys().forEach(filename => req(filename)); } configure(loadStories, module);
とかで、storybook のファイルをちゃんと読むようにする。
webpack のバージョン 4以下つかってない?という謎エラー
それでも、webpack のバージョン 4以下つかってない?という謎エラーがでる。。
ERR! Module build failed: Error: You may be using an old version of webpack; please check you're using at least version 4 ERR! at successfulTypeScriptInstance (/Users/xxxxxxxxxx/node_modules/ts-loader/dist/instances.js:168:15) ERR! at Object.getTypeScriptInstance (/Users/xxxxxxxxxx/node_modules/ts-loader/dist/instances.js:51:12) ERR! at Object.loader (/Users/nakagawa/Git/xxxxxxxxxx/node_modules/ts-loader/dist/index.js:16:41) ERR! @ ./.storybook/config.js 4:2-59 ERR! @ multi ./node_modules/@storybook/react/dist/server/config/polyfills.js ./node_modules/@storybook/react/dist/server/config/globals.js ./.storybook/config.js
で、いろいろやり尽くした結果。storybook のコンポーネント作るファイル xxxx.story.tsx の方で読み込んでいる @storybook/*** 系アドオンのバージョンも全部 4.0.0-alpha.10 に揃えないとだめだった。
参考: