Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug] Unable to find local modules using resolve alias #316

Closed
torleifhalseth opened this issue Apr 6, 2022 · 21 comments
Closed

[Bug] Unable to find local modules using resolve alias #316

torleifhalseth opened this issue Apr 6, 2022 · 21 comments
Labels
bug Something isn't working needs reproduction

Comments

@torleifhalseth
Copy link

torleifhalseth commented Apr 6, 2022

Describe the bug

In our project, we are using Vue 3, Typescript, and Vite.
In our Vite config and Typescript configuration, we specify the alias to import local modules.

vite.config.js
resolve: { alias: { "@": path.resolve(__dirname, "./src"), }, },

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

It is working as expected when we are running the project using Vite.

In storybook i used this configuration to enable the same custom alias:
module.exports = { framework: "@storybook/vue3", stories: ["../src/**/*.stories.@(js|jsx|ts|tsx)"], core: { builder: "@storybook/builder-vite" }, async viteFinal(config, { configType }) { return mergeConfig(config, { resolve: { alias: { "@": path.resolve(__dirname, "../src") }, }, }); }, };

When running Storybook we get this error:
"Neither '@/mixins/wizardMixin.vue' nor '@/mixins/wizardMixin.js(x)' or '@/mixins/wizardMixin/index.js(x)' or '@/mixins/wizardMixin/index.ts(x)' could be found in 'C:/repos/pia-app/frontend/src/views/wizards/travel'"

The actual file is @/mixins/wizardMixin.ts. I tried changing the file name to index.ts, but it is still not resolved.

Expected behavior

I was expecting the resolver to work in builder-vite as it does when running vite.

Screenshots and/or logs

image

@torleifhalseth torleifhalseth added the bug Something isn't working label Apr 6, 2022
@IanVS
Copy link
Member

IanVS commented Apr 6, 2022

@thalseth would you be willing to make a reproduction of this, so we can look into it? Another thing you can try is creating the new config using mergeConfig, and then logging out the result before returning it, in case it's not what you're expecting.

@torleifhalseth
Copy link
Author

torleifhalseth commented Apr 6, 2022

Thanks for the immediate response @IanVS!

If you look at the screenshot I posted it looks like the resolver is trying to find the module in the context of the file importing it :(

I am experiencing the same issue using the mergeConfig function. Here is the code and result when logging.

It looks like the resolve alias is defined as expected.

module.exports = { framework: "@storybook/vue3", stories: ["../src/**/*.stories.@(js|jsx|ts|tsx)"], addons: [ "@storybook/addon-links", "@storybook/addon-essentials", "@storybook/preset-scss", ], core: { builder: "@storybook/builder-vite" }, async viteFinal(config, { configType }) { // return the customized config const mergedConfig = mergeConfig(config, { // customize the Vite config here resolve: { alias: { "@": path.resolve(__dirname, "../src/") }, }, }); console.log(mergedConfig); return mergedConfig; }, };

{ configFile: false, root: 'C:\\repos\\pia-app\\frontend', cacheDir: 'node_modules/.vite-storybook', envPrefix: [ 'VITE_', 'STORYBOOK_' ], define: {}, resolve: { alias: { vue: 'vue/dist/vue.esm-bundler.js', '@': 'C:\\repos\\pia-app\\frontend\\src' } }, plugins: [ { name: 'storybook-vite-code-generator-plugin', enforce: 'pre', configureServer: [Function: configureServer], config: [Function: config], configResolved: [Function: configResolved], resolveId: [Function: resolveId], load: [AsyncFunction: load], transformIndexHtml: [AsyncFunction: transformIndexHtml] }, { name: 'mock-core-js', resolveId: [Function: resolveId], load: [Function: load] }, { name: 'storybook-vite-source-loader-plugin', enforce: 'pre', transform: [AsyncFunction: transform] }, [ [Object], [Object] ], { name: 'storybook-vite-inject-export-order-plugin', enforce: 'post', transform: [AsyncFunction: transform] }, { name: 'vite:vue', handleHotUpdate: [Function: handleHotUpdate], config: [Function: config], configResolved: [Function: configResolved], configureServer: [Function: configureServer], resolveId: [AsyncFunction: resolveId], load: [Function: load], transform: [Function: transform] }, { name: 'vue-docgen', transform: [AsyncFunction: transform] } ], server: { middlewareMode: true, hmr: { port: 6006, server: [Server] }, fs: { strict: true } }, optimizeDeps: {...}

@IanVS
Copy link
Member

IanVS commented Apr 6, 2022

Hmmmm, yeah sorry, without a repo that I can poke around with, I'm not sure how much help I can be here, unfortunately.

@torleifhalseth
Copy link
Author

I tried creating a repo to poke around with here https://stackblitz.com/edit/vitejs-vite-dg7twk @IanVS, but for some reason, storybook is not running as expected 🤷‍♂️

@IanVS
Copy link
Member

IanVS commented Apr 6, 2022

Sometimes it's easier to just create a repository with npm create vite@latest, follow the prompts and install dependencies, then run npx sb@next init. Then it's a matter of tweaking it to show the behavior you're seeing, and pushing it up to github. Sorry it's a bit of a pain, we'll try to make it easier in the future.

@torleifhalseth
Copy link
Author

torleifhalseth commented Apr 7, 2022

I created a local repo and tried to replicate the issue, but the custom resolver alias is working as expected in this project using the same dependencies and configuration 🤷‍♂️

The only difference is that the original repo has a lot of files with a deeper folder structure, but when trying to replicate this it is also working as expected.

I tried adjusting the blob to define where to retrieve stories from, specifying a single folder with stories that do not reference any of the components using resolver alias. What I notice is that some part of running "npm run storybook" is scanning all files even though the blob is specifying a single folder or file. Do you have any idea why this happens @IanVS and if this might be an issue related to vue-docgen-api https://vue-styleguidist.github.io/docs/Docgen.html#api scanning everything?

image

@IanVS
Copy link
Member

IanVS commented Apr 7, 2022

Do you have any idea why this happens @IanVS and if this might be an issue related to vue-docgen-api vue-styleguidist.github.io/docs/Docgen.html#api scanning everything?

Yes, vue-docgen needs to scan all of your vue components so that it can gather docs information to show in the args table and docsPage.

Is that causing problems for you, or just unexpected?

@torleifhalseth
Copy link
Author

Ok, maybe vue-docgen does not like some of the Vue APIs we are using? We are using both Vue 2 and Vue 3 APIs 🤔

When removing the imports mentioned above I don't get any error on other named alias imports. The imports are used as Vue mixins and that might be a feature vue-docgen does not support, or maybe the content of the mixins is unsupported.

Now it just states: "The passed source is empty".

image

@IanVS
Copy link
Member

IanVS commented Apr 7, 2022

And this is still not something you're able to reproduce in a fresh repository? If you can, I'll try to help take a look.

@torleifhalseth
Copy link
Author

No, not able to reproduce this. I just tested to add a mixin in my fresh repository, but it is working as expected there. The test mixin is simplified but I guess this shows that using mixins is not the problem.

@torleifhalseth
Copy link
Author

Woop, I just caught the same warning output in the reproduced repository using mixins now. I did not see it immediately because the storybook was showing all components as expected. I will create the reproduction and post it when available on Github.

For some reason, I am not able to push directly to Github from this enterprise computer 🙈

Thanks for hanging in there @IanVS 🍻

@IanVS
Copy link
Member

IanVS commented Apr 7, 2022

It seems like vue-docgen-api might not have full vue3 compatibility: vue-styleguidist/vue-styleguidist#997 (comment), and I also found vue-styleguidist/vue-styleguidist#1191 which might be related. Overall though, this does seem like it's probably a vue-docgen-api issue, doesn't it?

I also found vue-styleguidist/vue-styleguidist#359 (comment) which could help, maybe.

@IanVS
Copy link
Member

IanVS commented Apr 7, 2022

That said, it shouldn't error out, and so I think that's a bug we need to fix here. Your reproduction will help a lot with that, if/when you're able to push it up.

@torleifhalseth
Copy link
Author

torleifhalseth commented Apr 7, 2022

Sorry it took so long: https://github.com/thalseth/vite-project
I had to use file upload to get it out there...

I will look at the issues you posted now.

@IanVS
Copy link
Member

IanVS commented May 13, 2022

@torleifhalseth, sorry it took so long to get back to this, but I pulled down your repo and tried to run it, but it's missing a storybook config file (.storybook/main.js). Do you perhaps have some local commits that you haven't pushed up?

@rafael-telles
Copy link

Hey guys, any updates on this? I am trying to deal with this bug in a private repo (migrating from webpack builder) but have no idea of what to try next...

@IanVS
Copy link
Member

IanVS commented Jun 14, 2022

@rafael-telles if you can provide a reproduction, I can try taking a look. The one provided by @torleifhalseth was incomplete.

@augustoody
Copy link

For anyone that might be facing this too, in my case, it seemed to be all related to how We use the resolve.alias. After trying another fix from a different thread here (that asked to remove some dependencies from preview.jsx, I found that my alias to @/components that was supposed to parse my app folder was all broken up.

Taking a look at the config coming back from viteFinal, it was setting the root folder as by .storybook folder. To my case just using the resolve.alias like this fixed it:

const path = require('path');

const toPath = (filePath) => path.join(process.cwd(), filePath);

module.exports = {
async viteFinal(config, { configType }) {
    ...,
    return mergeConfig(config, {
      resolve: {
        alias: {
          '@': toPath('app')
        }
      }
    });
  }
};

@IanVS
Copy link
Member

IanVS commented Oct 7, 2022

Thanks @augustoody

@IanVS IanVS closed this as not planned Won't fix, can't repro, duplicate, stale Oct 7, 2022
@uturnr
Copy link

uturnr commented Apr 14, 2023

I was not having luck with vue-docgen picking up my aliases. I may be doing something wrong in my config, and I am stuck on older versions of some libraries. I created a patch in the meantime. My temporary hack is not working with vite-tsconfig-paths but it is working for me with vite config { resolve: { alias: { '@': 'somePath', ... } } } (I wrote a separate function to extract these from my tsconfig.json)

I thought I would share it in case it is useful for somebody, or in case there is an actual bug still.

The file I was trying to import was controller.ts. The error messages I was getting were:

Neither '@components/buttons/SelectableButton/controller.vue' nor '@components/buttons/SelectableButton/controller.js(x)' or '@components/buttons/SelectableButton/controller/index.js(x)' or '@components/buttons/SelectableButton/controller/index.ts(x)' could be found in '(redacted)/src/components/buttons/SelectableButton'
No suitable component definition found on "(redacted)/src/components/buttons/SelectableButton/SelectableButton.vue"

I made some changes to the vueDocgen function within /node_modules/@storybook/builder-vite/dist/plugins/vue-docgen.js:

function vueDocgen(vueVersion) {
    // Patch - Use the aliases from the vite config. Var defined to store config.
    let config;

    return {
        name: 'vue-docgen',
        // Patch - Set config var.
        configResolved(resolvedConfig) {
            config = resolvedConfig
        },
        async transform(src, id) {
            // Patch - Shape resolvedConfig alias back into object format.
            const aliasArray = config.resolve.alias;
            const alias = aliasArray.reduce((aliasObj, value) => {
                const { find, replacement } = value;
                if (find && replacement) {
                    aliasObj[find] = replacement;
                }
                return aliasObj;
            }, {});
            if (/\.vue$/.test(id) && !/\.stories\.vue$/.test(id)) {
                // Patch - `alias` in the object format can be passed as 2nd arg
                // to vue-docgen-api.parse
                const metaData = await (0, vue_docgen_api_1.parse)(id, alias);
                const metaSource = JSON.stringify(metaData);
                const s = new magic_string_1.default(src);
                const componentLocation = vueVersion === 3 ? '_sfc_main' : '__component__.exports';
                s.append(`;${componentLocation}.__docgenInfo = ${metaSource}`);
                return {
                    code: s.toString(),
                    map: s.generateMap({ hires: true, source: id }),
                };
            }
        },
    };
}

Storybook - 6.5.16
@storybook/builder-vite - 0.4.2
Vite - 4.2.1
Vue - 2.7.14
vue-docgen-api - 4.60.0 (locked to this version as not ready to upgrade node)
vite-tsconfig-paths - 4.2.0 (not compatible with my solution, no longer using)

@katerberg
Copy link

I know this is closed and you need a reproduction case, but just adding a data point that this is biting me too.

It seems related to storybookjs/storybook#9695 since the only thing throwing these warnings are files in @/mixins.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working needs reproduction
Projects
None yet
Development

No branches or pull requests

6 participants