Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add typescript paths to storybook

I have a react application with a custom Webpack configuration. After adding Webpack aliases that matches tsconfig.json file compilerOptions->paths field the aliases were recognized by webpack.

Since storybook comes with a built in Webpack configuration, my aliases are not read by Storybook and I'm getting the following error:

Module not found: Error: Can't resolve <path with typescript alias> in <some folder path>
like image 442
Noy Oliel Avatar asked Sep 12 '25 16:09

Noy Oliel


2 Answers

In Storybook main.js file, add the following:

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
  ...,
  webpackFinal: async (config, { configType }) => {
       config.resolve.plugins = [new TsconfigPathsPlugin()];<-- this line
       return config;
  }

};

You can install tsconfig-paths-webpack-plugin using the following command from the folder in which your application's package.json file resides:

npm i tsconfig-paths-webpack-plugin -D

Solution was derived from this discussion: https://github.com/storybookjs/storybook/issues/6316

like image 111
Noy Oliel Avatar answered Sep 15 '25 06:09

Noy Oliel


For future vistors of this question, since 15th July of 2022 storybooks can use Vite instead Webpack.

In that case I recommend using vite-tsconfig-paths instead of tsconfig-paths-webpack-plugin. If you are using TS paths in Vite, you probably already have this package installed.

Add this to your .storybook/main.js

const { mergeConfig } = require("vite")
const { default: tsconfigPaths } = require('vite-tsconfig-paths')

module.exports = {
  // your previous configs and more...
  viteFinal(config, { configType }) {
    return mergeConfig(config, {
      plugins: [
        tsconfigPaths()
      ]
    })
  }
}
like image 41
kpostekk Avatar answered Sep 15 '25 07:09

kpostekk