Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storybook config in typescript

I would like to write storybook decorator. Is there any way to write it and preview.js in typescript?

I already succeeded in writing stories itself in TS, and now would like to write storybook config in TS.

like image 216
Yaroslav Kishchenko Avatar asked Dec 11 '25 22:12

Yaroslav Kishchenko


2 Answers

Since storybook 6.3, you can write main.ts and preview.ts in typescript. See the example in the 6.3.0 release here.

Note: If you use a newer version than 6.3.0, change the tag filter in the repository link above to match and locate a similar example in case the syntax has changed.

However, the caveat here is that you cannot use {"target": "ESNext"} in your typical tsconfig.json because node doesn't support ES module natively, yet.

If you want ESNext, for example using storybook alongside rollup, a workaround is needed. My approach is to configure storybook to use another tsconfig.json via the environment variable TS_NODE_PROJECT. For example

.storybook/tsconfig.json

{
  "extends": "..",
  "compilerOptions": {
    "module": "commonjs",
    "target": "ES2017"
  }
}

Then run cross-env TS_NODE_PROJECT=.storybook/tsconfig.json start-storybook.

The reason it works because storybook uses webpack which in turn using tsconfig-paths to resolve the path for tsconfig.json.

like image 183
Alvis Avatar answered Dec 14 '25 11:12

Alvis


I finally manage to make it works.

  • Configs directory should be added to include option of typescript preset and tsconfig.json
  • Set module resolution to "node", because for some reasons it got set to "classic" for config folder

Also, main.js should stay JS file, because only after parsing main.js config, storybook able to use TS preset.

like image 36
Yaroslav Kishchenko Avatar answered Dec 14 '25 12:12

Yaroslav Kishchenko