Skip to content

Cant add aliases in storybook config #11989

Closed

Description

@toastyboost

Cant add aliases to storybook 6^
main.js

const path = require("path");

module.exports = {
  webpackFinal: async (config) => {
    config.resolve.alias = {
      ...config.resolve.alias,
      "~/": path.resolve(__dirname, "../src/"),
    };
    config.resolve.extensions.push(".ts", ".tsx");
    return config;
  },
};

{
  "compilerOptions": {
    "allowJs": false,
    "allowSyntheticDefaultImports": true,
    "baseUrl": ".",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["dom", "dom.iterable", "esnext"],
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "rootDirs": ["src", "stories"],
    "outDir": "./dist",
    "strict": true,
    "skipLibCheck": true,
    "target": "es6",
    "typeRoots": ["./node_modules/@types"],
    "paths": {
      "~/": ["./src/"]
    }
  },
  "exclude": ["./node_modules", "./dist"],
  "include": ["src", "stories"]
}

error

Module not found: Error: Can't resolve '~/' in '/Users/user/dev/storybook-starter/stories'
 @ ./stories/develop.stories.tsx 54:0-31 57:13-22 72:25-34
 @ ./stories sync nonrecursive ^\.\/(?:(?!\.)(?=.)[^/]*?\.stories\.(ts|tsx))$
 @ ./.storybook/generated-stories-entry.js
 @ multi ./node_modules/@storybook/core/dist/server/common/polyfills.js ./node_modules/@storybook/core/dist/server/preview/globals.js ./.storybook/storybook-init-framework-entry.js ./node_modules/@storybook/addon-docs/dist/frameworks/common/config.js-generated-other-entry.js ./node_modules/@storybook/addon-docs/dist/frameworks/react/config.js-generated-other-entry.js ./node_modules/@storybook/addon-actions/dist/preset/addDecorator.js-generated-other-entry.js ./node_modules/@storybook/addon-actions/dist/preset/addArgs.js-generated-other-entry.js ./.storybook/preview.js-generated-config-entry.js ./.storybook/generated-stories-entry.js (webpack)-hot-middleware/client.js?reload=true&quiet=false&noInfo=undefined

files
Screenshot 2020-08-13 at 18 33 57

What i am doing wrong?

Activity

  1. tooppaaa commented on Aug 14, 2020

    @tooppaaa
    Contributor

    Without thinking too far, I think updating config object might not work as expected.
    A simple workaround for you @toastyboost

    webpackFinal: async (config) => {
        return {
          ...config,
          resolve: {
            ...config.resolve,
            alias: {
              ...config.resolve?.alias,
              ...aliases,
            },
          },
        };
      },

    In addition with 0 config typescript, you no longer need config.resolve.extensions.push(".ts", ".tsx");

  2. silouanwright commented on Aug 14, 2020

    @silouanwright

    I'm running into this as well and I assume this will break a lot of Storybook devs experience.

        config.resolve.modules = [
          ...(config.resolve.modules || []),
          path.resolve('../')
        ]
    

    This is what I had before that allowed to resolve to my root path properly, but for whatever reason this doesn't help in my upgrade.

  3. ndelangen commented on Aug 17, 2020

    @ndelangen
    Member

    If someone could create a reproduction repo, that'd be super helpful fixing this bug.

    if this doesn't work

    const path = require("path");
    
    module.exports = {
      webpackFinal: async (config) => {
        config.resolve.alias = {
          ...config.resolve.alias,
          "~/": path.resolve(__dirname, "../src/"),
        };
        config.resolve.extensions.push(".ts", ".tsx");
        return config;
      },
    };

    then that's a bug.

  4. added
    needs reproduction
    on Aug 17, 2020
  5. gavmck commented on Sep 3, 2020

    @gavmck

    I just came across this after having some issues having upgraded storybook to 6.

    Turned out my problem was an incorrect resolve function for whatever reason.

    My main.js is in .storybook and I am using this function:

    function resolve(dir) {
      return path.join(__dirname, dir)
    }

    Example:

    alias: {
      '@': resolve('../src'),
    },

    Otherwise the same setup described by @ndelangen above and it is working.

  6. chrisbutler commented on Sep 17, 2020

    @chrisbutler
    Contributor

    this was working fine for me with Storybook 5.x, but is now broken in 6.x

    the exact scenario described by @ndelangen is not working for me, so i'm inclined to believe that this is a bug

    i also still see info => Using default Webpack setup. in the console, even though i am providing custom config like so:

    const webpackConfig = require('../.webpack/client.js');
    
    module.exports = {
      webpackFinal: (config) => ({
        ...config,
        resolve: {
          ...config.resolve,
          ...webpackConfig.resolve,
          alias: {
            ...config.resolve.alias,
            ...webpackConfig.resolve.aliases,
          },
        },
      }),
      //other config properties
    }
  7. mattrothenberg commented on Sep 23, 2020

    @mattrothenberg
    Contributor

    I'm also running into this issue, having tried the solution here #11989 (comment).

    @ndelangen Check out this repro repository – https://github.com/mattrothenberg/sb6-resolve-alias-error

    You should be able to clone, run yarn && yarn storybook and see that the tilde ("~") alias doesn't resolve for the Button component.

  8. added and removed
    needs reproduction
    on Sep 24, 2020
  9. JanJakes commented on Oct 23, 2020

    @JanJakes
    Contributor

    I think the problem may be trailing slashes. Try using ~ and ../src/ exactly. It seems to work for me in all the variants below (Storybook 6.0.21 and 6.0.27).

    Shortest:

    webpackFinal: async (config) => {
      config.resolve.alias['~'] = path.resolve(__dirname, '../src/');
      return config;
    },

    Short:

    webpackFinal: async (config) => {
      config.resolve.alias = {
        ...config.resolve?.alias,
        '~': path.resolve(__dirname, '../src/'),
      };
      return config;
    },

    Longer:

    webpackFinal: async (config) => ({
      ...config,
      resolve: {
        ...config.resolve,
        alias: {
          ...config.resolve?.alias,
          '~': path.resolve(__dirname, '../src/'),
        },
      },
    }),
  10. 19 remaining items

  11. Alecell commented on Apr 6, 2021

    @Alecell

    @TheDutchCoder seems like the config.resolve.alias['#'] = path.resolve(__dirname, '../src') doesn't have any effect.

    What the effect this shoud reach? Removing that line everything keeps working fine.

  12. camslice commented on Apr 28, 2021

    @camslice

    As per @TheDutchCoder , this works for me using Storyboard v6.2.9 and Vue 2. It configures an alias from @ to ../src and allows you to write relative imports from any folder, eg:

    import Button from '@/components/atoms/Button.vue';
    import MyMixin from '@/mixins/my-mixin.js';
    

    Add a webpackFinal key to ./.storybook/main.js:

    const path = require("path")
    
    module.exports = {
      "stories": [ ... ],
      "addons": [ ... ],
      "webpackFinal": async (config) => {
        config.resolve.alias['@'] = path.resolve(__dirname, '../src')
        return config
      }
    }
    
  13. mdirshaddev commented on May 16, 2021

    @mdirshaddev

    This works properly for me on the latest version:

    const path = require("path")
    
    module.exports = {
      "webpackFinal": async (config) => {
        config.resolve.alias['#'] = path.resolve(__dirname, '../src')
        config.resolve.alias['#components'] = path.resolve(__dirname, '../src/components')
        return config
      }
    }

    I was struggling to find the solution and then i found yours solution. By the way i was missing a double quotes on webpackFinal. That's all. Thanks

  14. maxim-c commented on Jun 4, 2021

    @maxim-c

    hmmm, I can't get why alias @ works but ~ is not... Spend pretty good amount of time trying to setup with ~, thinking that something wrong with config itself... 🤯

    works fine:

        config.resolve.alias['@'] = path.resolve(__dirname, '../src')
    
        config.module.rules.push({
          test: /\.scss$/,
          use: [
            'style-loader', 
            'css-loader',
            {
              loader: "sass-loader",
              options: {
                additionalData: '@import "@/assets/scss/utils";',
              },
            }, 
          ],
        });

    SassError: SassError: Can't find stylesheet to import: @import "~/assets/scss/utils";

        config.resolve.alias['~'] = path.resolve(__dirname, '../src')
    
        config.module.rules.push({
          test: /\.scss$/,
          use: [
            'style-loader', 
            'css-loader',
            {
              loader: "sass-loader",
              options: {
                additionalData: '@import "~/assets/scss/utils";',
              },
            }, 
          ],
        });
  15. hcl-bpchasse commented on Jun 25, 2021

    @hcl-bpchasse

    When I encountered this issue, I was expecting the aliases to resolve correctly for files in the .storybook/ directory. What I found was that it seems the aliases are not for resolving in the .storybook/ directory (.storybook "config" files?), but instead for resolving when running the Storybook webpack build (npm run storybook).

    One thing we noted was that our custom React "add on" component, being registered in.storybook/register.js, was being resolved like the other files in the .storybook/ directory.

    We resolved our issue by using relative paths for .storybook/ files and addons, and are leveraging aliases, as described in this issue, for our actual Storybook story files.

    For our working Storybook webpack server aliases, we configured .storybook/main.js like:

    // .storybook/main.js
    
    const webpackConfig = require('../webpack.config')
    
    module.exports = {
      webpackFinal: (config) => {
        config.resolve.alias = {
          ...webpackConfig.resolve.alias,
          ...config.resolve.alias,
        }
        return config;
      },
    };

    Thanks All!

  16. faatihi commented on Jul 3, 2021

    @faatihi

    Late to the party, but I had to change my choice of character.
    I changed $ to @ and it now works fine

    -   config.resolve.alias['$'] = path.resolve(__dirname, '../src/components/')
    -   config.resolve.alias['$utils'] = path.resolve(__dirname, '../src/utils/')
    +   config.resolve.alias['@'] = path.resolve(__dirname, '../src/components/')
    +   config.resolve.alias['@utils'] = path.resolve(__dirname, '../src/utils/')
  17. gaurav5430 commented on Jul 7, 2021

    @gaurav5430

    Had the same issue in latest storybook 6.3.3
    In my case the issue was the trailing slash, as mentioned by @JanJakes here:
    #11989 (comment)

    instead of ~/ i had to use ~

  18. lParanhos commented on Aug 9, 2021

    @lParanhos

    For me, using NextJs, this is solved the problem:

    /.storybook/main.js
    
    const path = require('path')
    module.exports = {
       // ...others configs
       
       
        webpackFinal: async (config) => {
          config.resolve.modules = [
            ...(config.resolve.modules || []),
            path.resolve(__dirname, "../"),
          ];
    
          config.resolve.alias = {
            ...config.resolve.alias,
            '@components': path.resolve(__dirname, '../components'),
            '@public': path.resolve(__dirname, '../public'),
            '@styles': path.resolve(__dirname, '../styles')
          }
      
          return config;
        },
      }
    
  19. Razzwan commented on Oct 26, 2021

    @Razzwan

    It works without slashes:

    const path = require("path");
    
    module.exports = {
    	addons: ['@storybook/addon-links', '@storybook/addon-essentials'],
    	stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],
    	webpackFinal: (config) => {
    		config.resolve.alias = {
    			...config.resolve.alias,
    			"~": path.resolve(__dirname, "../src"),
    		};
    		return config;
    	},
    };
  20. TheDutchCoder commented on Dec 20, 2021

    @TheDutchCoder

    I don't work with webpack anymore, but doesn't the ~ character have a special meaning in a webpack context? I thought it wasn't meant to be used as an identifier for your own resolvers (same as with @since npm packages can now use that and result in conflicts).

    It's also the reason I used # in my example.

  21. shirakaba commented on Mar 25, 2022

    @shirakaba

    Here's how I was able to resolve tsconfig path aliases in a React + TypeScript + Vite Storybook project, in case any other lost souls end up here: How to resolve aliases in Storybook? – Stackoverflow. The thread also details equivalent solutions for Webpack.

  22. shadowmint commented on May 31, 2022

    @shadowmint

    I know this is an old ticket with numerous "try this" things listed in it, but fundamentally, the issue is reproducible by doing this:

    npm init vue@latest

    Select:

    ✔ Project name: … foo
    ✔ Add TypeScript? … Yes
    ✔ Add JSX Support? … No 
    ✔ Add Vue Router for Single Page Application development? … No 
    ✔ Add Pinia for state management? … No 
    ✔ Add Vitest for Unit Testing? … No 
    ✔ Add Cypress for both Unit and End-to-End testing? … No 
    ✔ Add ESLint for code quality? … No
    

    Now install storybook

    cd foo
    npx storybook init
    npm install
    

    Now create a basic component:

    <script setup lang="ts">
    import HelloWorld from '@/components/HelloWorld.vue'  // <--- Using an alias
    </script>
    
    <template>
      <div>
        <hello-world msg="hi"/>
      </div>
    </template>
    
    <style scoped>
    </style>
    

    and a basic story:

    import Hello from './Hello.vue';
    
    export default {
        title: 'Hello',
        component: Hello,
        argTypes: {},
    };
    
    export const Default = () => ({
        components: {Hello},
        setup: () => ({}),
        template: `<hello/>`,
    });
    
    

    and run:

    npm run storybook

    You will see:

    Screen Shot 2022-05-31 at 8 34 08 pm

    8:33:34 pm [vite] Internal server error: Failed to resolve import "@/components/HelloWorld.vue" from "src/components/Hello.vue". Does the file exist?
      Plugin: vite:import-analysis
      File: /Users/doug/dev/nest-rpg/foo/src/components/Hello.vue
      1  |  import { defineComponent as _defineComponent } from "vue";
      2  |  import HelloWorld from "@/components/HelloWorld.vue";
         |                          ^
      3  |  const _sfc_main = /* @__PURE__ */ _defineComponent({
      4  |    name: "Hello",
    

    ...but why?

    Well, bluntly because the storybook configuration is wrong.

    The automatically generated vite config for storybook and the vite config from the vue scaffold are different; the scaffold looks like this:

    export default defineConfig({
      plugins: [vue(), vueJsx()],
      resolve: {
        alias: {
          '@': fileURLToPath(new URL('./src', import.meta.url))
        }
      }
    })
    

    and tsconfig.json that says:

      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@/*": ["./src/*"]
        }
      },
    

    and .storybook/main.js doesn't load that file. Or doesn't process it. Or something.

    If you modify main.js to have this import, it works, eg:

    const { mergeConfig } = require('vite');
    const path = require("path");
    
    module.exports = {
      ...
      "features": {
        "storyStoreV7": true
      },
      async viteFinal(config, { configType }) {
        return mergeConfig(config, {
          resolve: {
            alias: { '@': path.resolve(path.dirname(__dirname), "src")},
          },
        });
      },
    

    So is this an issue or not?

    Well, lets put it this way.

    Anyone who uses the official (https://vuejs.org/guide/quick-start.html#with-build-tools) vue scaffold, with the official storybook install (https://storybook.js.org/docs/vue/get-started/install), will get an 'out of the box' copy of storybook that is broken.

    I don't know why this issue is closed with 'completed' because a work around exists, but, for anyone who finds this post, no, it's not just you, it's broken.

    If you feel strongly about it, consider opening a new issue, a PR...

    ...but please appreciate that fundamentally the reason this is broken is because the alias is defined in the root configuration files, and those files are not used by storybook; the version generated by storybook does not include them; if you want to fix it, you need to look at what your configuration actually does and back port that into the storybook config, not just randomly copy and paste changes from this thread.

  23. sunflowerseastar commented on Dec 16, 2023

    @sunflowerseastar

    I'm using Nextjs 14 and Storybook 7.5/7.6, and my co-worker really wanted a custom ~ alias for whatever reason, sigh. Anyway, I got this working like this, based on @lParanhos solution above (thank you!):

      webpackFinal: async (config: any) => ({
        ...config,
        resolve: {
          ...config.resolve,
          alias: {
            ...config.resolve.alias,
            '~': path.resolve(__dirname, '../'),
          },
        },
      }),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions