Out of the box, you can't write stories using TypeScript within a CRA generated application since the webpack config is only setup to process regular .js
and .jsx
files. Not to worry! We're going to fix that by creating our own webpack config where we'll specify the additional things in order to get it working with our TypeScript components.
Step 1
The first thing you'll have to do is install a TypeScript loader. For this tutorial, I've chosen awesome-typescript-loader
as it was recommended on the Storybook website. Note: This package should be saved as a dev dependency, which we can do by adding the -D
flag.
yarn add -D awesome-typescript-loader
This will allow us to process TypeScript files in our story files.
Step 2
Once you've got this dependency installed, you'll need to configure the actual webpack config. To do this, we'll need to create a separate file in order to configure our build server within the .storybook
directory.
// .storybook/webpack.config.js
module.exports = ({ config }) => {
config.module.rules.push({
test: /\.(ts|tsx)$/,
use: [
{
loader: require.resolve('awesome-typescript-loader'),
},
],
});
config.resolve.extensions.push('.ts', '.tsx');
return config;
};
Here we're informing webpack that it should use the awesome-typescript-loader
whenever it encounters a .ts
or .tsx
file, something that it didn't know what to do with before.
Step 3
We're almost done! Next up, I updated the Storybook config file extension to .ts
and updated the imported file extensions from .jsx
to .tsx
. Note: The ?
character is a regex expression that marks the preceding character as optional -- this allows us to include both .ts
and .tsx
in a shorthanded manner.
// .storybook/config.ts
import { configure } from '@storybook/react';
// automatically import all files ending in *.stories.js
configure(require.context('../src', true, /\.stories\.tsx?$/), module);
And that's it! Now, we can write stories by importing our TypeScript React components.
Top comments (2)
how would i optionally use files passed in through the command line instead of:
i already have an npm script
npm run storybook
that calls"node --max-old-space-size=4096 node_modules/.bin/start-storybook -p 9002 -c .storybook/"
and i'd like to just be able to either search for all stories or be able to type:
npm run storybook src/thing/thing.stories.tsx
to run on a single file
is it necessary to do all that stuff? In the documentation says:
What I did what this:
And it worked, but I'm not sure if it's the right way of doing it