Skip to content

alias '@' to path.resolve(__dirname, './src') is not working #279

Closed

Description

@hronro

Describe the bug

Alias { '@': path.resolve(__dirname, './src') } is not working.

Reproduction

project structure:

vite.config.js
src
├── app.js
├── index.js

vite.config.js:

const path = require('path');

module.exports = {
  alias: {
    '@': path.resolve(__dirname, './src'),
  }
};

src/index.js

import { Foo } from '@/app';

Got error in vite:

[vite] Failed to resolve module import "@/app"

System Info

  • required vite version: 0.17.0
  • required Operating System: Linux
  • required Node version: 14.3.0

Activity

  1. remyz17 commented on May 27, 2020

    @remyz17

    Vite alias don't work like webpack does.
    You need to use resolvers to do what you want to do.

  2. hronro commented on May 27, 2020

    @hronro
    ContributorAuthor

    @remyz17
    I tried this code, but it doesn't work either:

    const path = require('path');
    const srcPath = path.resolve(__dirname, './src');
    
    module.exports = {
      resolvers: [{
        alias (id) {
          if (id.startsWith('@/')) {
            return path.join(srcPath, id.slice(2));
          }
        }
      }],
    };
  3. remyz17 commented on May 27, 2020

    @remyz17

    I guess you need to implement this 2 functions.
    requestToFile and fileToRequest

    Take a look at this code
    https://github.com/vuejs/vitepress/blob/master/src/node/resolver.ts#L19

  4. remyz17 commented on May 27, 2020

    @remyz17

    i tried to do it and it's not fully working.
    For exemple it don't work inside vue template: <img src="/@/..." />

    module.exports = {
      outDir: '../app/static',
      resolvers: [{
        requestToFile: publicPath => {
          if (publicPath.match(/^\/@\//)) {
            return path.join(srcPath, publicPath.replace(/^\/@\//, ''))
          }
        },
        fileToRequest: filePath => {
          if (filePath.startsWith('/src')) {
            return `/@/${path.relative(srcPath, filePath)}`
          }
        }
      }]
    }
    

    I noticed that we can not use @/ because it’s recognised as a node module so I used /@/

  5. hronro commented on May 27, 2020

    @hronro
    ContributorAuthor

    @remyz17
    This not works for me. In my case, the function fileToRequest is not even be called, and I'm still figuring out why.

  6. remyz17 commented on May 27, 2020

    @remyz17

    @remyz17

    This not works for me. In my case, the function fileToRequest is not even be called, and I'm still figuring out why.

    Send your vite config so i can take a look

  7. hronro commented on May 27, 2020

    @hronro
    ContributorAuthor

    @remyz17
    OK, here is my config:

    // vite.config.ts
    import * as path from 'path';
    
    import * as reactPlugin from 'vite-plugin-react';
    
    import type { UserConfig } from 'vite';
    
    const srcPath = path.resolve(__dirname, './src');
    
    const config: UserConfig = {
      jsx: 'react',
      alias: {
        'exenv': 'exenv-esm',
        'prop-types': 'es-react/prop-types.js',
      },
      resolvers: [{
        fileToRequest (filePath) {
          console.log('@@@', filePath);
          if (filePath.startsWith(srcPath)) {
            return `/@/${path.relative(srcPath, filePath)}`;
          }
        },
        requestToFile (publicPath) {
          if (publicPath.startsWith('/@/')) {
            return path.join(srcPath, publicPath.replace(/^\/@\//, ''));
          }
        },
      }],
      root: './src',
      plugins: [reactPlugin],
    };
    
    export default config;
  8. yyx990803 commented on May 27, 2020

    @yyx990803
    Member

    I think we probably will eventually provide an easier way to alias src directories. If your resolver is not working, it's better to provide a full reproduction instead of a single config file.

  9. hronro commented on May 28, 2020

    @hronro
    ContributorAuthor
  10. yyx990803 commented on May 28, 2020

    @yyx990803
    Member

    btw you don't need an alias like that... you can just do /main.js because that's the server root.

  11. hronro commented on May 28, 2020

    @hronro
    ContributorAuthor

    @yyx990803
    that should work, but I personally don't like to do that, because a path starts with / make me thought it's a file under the / folder of my file system.
    And could you review my code of the resolver, am I doing something wrong or it's a bug of vite?

  12. yyx990803 commented on May 28, 2020

    @yyx990803
    Member

    It's a bug. It's fixed in 801951e but it also adds an easier way to alias a directory so you can just do

    // vite.config.js
    module.exports = {
      alias: {
        '/@/': path.resolve(__dirname, './src')
      }
    }
  13. hronro commented on May 29, 2020

    @hronro
    ContributorAuthor

    @yyx990803
    Still doesn't work for after I upgrade vite to v0.18.0.
    https://codesandbox.io/s/vite-src-alias-demo2-lzpm0

  14. 22 remaining items

  15. csulit commented on Apr 15, 2021

    @csulit

    It's working but TS flag this as an error.
    import AppLayout from '/@/components/AppLayout.vue'
    Try to change it to this

    TS is still flags the import. I don't know if this is the right way to do it, I already solve the issue by declaring this to tsconfig.json

        "baseUrl": "./src",
        "paths": {
          "@components/*": ["./components/*"]
        },
    
  16. nzhtrtlc commented on Apr 15, 2021

    @nzhtrtlc

    Can't we just define a resolver that resolves src folder so we don't have to use aliases ?
    import Button from components/Button;

    MyViteProject > src > components > Button

    how can resolve src folder in vite.config.js ?

  17. csulit commented on Apr 15, 2021

    @csulit

    It's working but TS flag this as an error.
    import AppLayout from '/@/components/AppLayout.vue'
    Try to change it to this

    resolve: { alias: [{ // /@/xxxx => src/xxx find: /^\/@/, replacement: path.resolve(__dirname, './src') }] },

    import HelloWorld from '/@/components/HelloWorld.vue'

    Cannot find module '/@/components/HelloWorld.vue' or its corresponding type declarations.

    Use // @ts-ignore

    I solve it by declaring this to tsconfig.json

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

    The error is gone and did not break any component in build.

    image

  18. slumtrimpet commented on Apr 20, 2021

    @slumtrimpet

    For what it's worth, adding the following to tsconfig.json makes typescript happy:

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

    BUT you still need to also add corresponding:

      resolve: {
        alias: [
          { find: '@components', replacement: '/src/components' },
        ]
      }
    

    to vite.config.js to make vite happy. Maybe that's obvious to most, but it wasn't to me. ;-)

  19. jgermade commented on Apr 24, 2021

    @jgermade

    Still no working for me with reactRefresh when npm run dev

    It works when npm run build and in any case when using a --template vue (@vitejs/plugin-vue)

    This is my vite.config.js:

    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [reactRefresh()],
      resolve: {
        alias: [
          { find: /^@(?=\/)/, replacement: path.resolve(__dirname, './src') }
        ],
      },
    })
  20. csulit commented on Apr 24, 2021

    @csulit

    Still no working for me with reactRefresh when npm run dev

    It works when npm run build and in any case when using a --template vue (@vitejs/plugin-vue)

    This is my vite.config.js:

    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [reactRefresh()],
      resolve: {
        alias: [
          { find: /^@(?=\/)/, replacement: path.resolve(__dirname, './src') }
        ],
      },
    })

    Mine is working fine with this config.

    {
      "compilerOptions": {
        "target": "ESNext",
        "lib": ["DOM", "DOM.Iterable", "ESNext"],
        "types": ["vite/client"],
        "baseUrl": "./src",
        "paths": {
          "@interfaces/*": ["./interfaces/*"],
          "@components/*": ["./components/*"],
          "@pages/*": ["./pages/*"],
          "@contexts/*": ["./contexts/*"],
          "@services/*": ["./services/*"],
          "@utilities/*": ["./utilities/*"]
        },
        "allowJs": false,
        "skipLibCheck": false,
        "esModuleInterop": false,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "module": "ESNext",
        "moduleResolution": "Node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react"
      },
      "include": ["./src"]
    }
    
    import reactRefresh from '@vitejs/plugin-react-refresh';
    import fs from 'fs';
    import lessToJs from 'less-vars-to-js';
    import path from 'path';
    import { defineConfig } from 'vite';
    import vitePluginImp from 'vite-plugin-imp';
    
    const themeVariables = lessToJs(
      fs.readFileSync(
        path.resolve(__dirname, './src/styles/variables.less'),
        'utf8'
      )
    );
    
    export default defineConfig({
      plugins: [
        reactRefresh(),
        vitePluginImp({
          libList: [
            {
              libName: 'antd',
              style: (name) => `antd/es/${name}/style/index`,
            },
          ],
        }),
      ],
      css: {
        preprocessorOptions: {
          less: {
            javascriptEnabled: true,
            modifyVars: themeVariables,
          },
        },
      },
      resolve: {
        alias: [
          {
            find: '@',
            replacement: path.resolve(__dirname, './src'),
          },
          {
            find: '@interfaces',
            replacement: path.resolve(__dirname, './src/interfaces'),
          },
          {
            find: '@components',
            replacement: path.resolve(__dirname, './src/components'),
          },
          {
            find: '@pages',
            replacement: path.resolve(__dirname, './src/pages'),
          },
          {
            find: '@contexts',
            replacement: path.resolve(__dirname, './src/contexts'),
          },
          {
            find: '@services',
            replacement: path.resolve(__dirname, './src/services'),
          },
          {
            find: '@utilities',
            replacement: path.resolve(__dirname, './src/utilities'),
          },
        ],
      },
    });
    
    
  21. jgermade commented on Apr 26, 2021

    @jgermade

    Thanks @csulit for your reply!

    Reviewing my code I've figured out that my scenario is a bit different... I mean:

    I've tested that using the alias works like a charm when index.html is on the root of the project, but does not work when moving index.html into src (using vite serve src)

    image

    Also noticed that when moving the index.html into src folder, I can import files from root (p.e. import App from '/App') which is great. The bad point is that IntelliSense is not useful...

    Using this jsconfig.json:

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

    Gets folloging sugestions:

    Captura de pantalla de 2021-04-26 13-42-56

    But when using root slash:

    Captura de pantalla de 2021-04-26 13-44-39

    Any ideas how to use this alias moving index.html into src folder?

    vite.config.js

    export default defineConfig({
      plugins: [reactRefresh()],
      resolve: {
        alias: [
          { find: /^@(?=\/)/, replacement: path.resolve(__dirname, './src') },
        ],
      },
    })
  22. SarcevicAntonio commented on May 2, 2021

    @SarcevicAntonio

    For what it's worth, adding the following to tsconfig.json makes typescript happy:

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

    BUT you still need to also add corresponding:

      resolve: {
        alias: [
          { find: '@components', replacement: '/src/components' },
        ]
      }
    

    to vite.config.js to make vite happy. Maybe that's obvious to most, but it wasn't to me. ;-)

    This worked for me! Using vite with Svelte and Typescript and this setup works perfectly with VSCode importing my files automatically.

    Thanks a bunch slumtrimpet

  23. ddzy commented on May 11, 2021

    @ddzy
    // vite.config.ts
    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [vue()],
      // 路径代理
      resolve: {
        alias: [
          { find: '@', replacement: '/src' },
          { find: 'views', replacement: '/src/views' },
          { find: 'components', replacement: '/src/components' },
        ]
      }
    })

    Working for me

  24. marialovesbeans commented on May 17, 2021

    @marialovesbeans

    Is there a way of specifying src as root import path? ex: in create-react-app you can set a baseUrl, so instead of writing

    import User from '~/src/components/User';
    

    You can write:

    import User from 'components/User';
    

    This looks much cleaner. How to achieve the same in Vite?

  25. marxangels commented on May 19, 2021

    @marxangels

    idea.config.js

    System.config({
      paths: {
        '@/*': './src/*',
      }
    })
  26. npearson72 commented on Jun 11, 2021

    @npearson72

    The following is working for me:

    ...
      resolve: {
        alias: {
          '@pages': path.resolve(__dirname, './src/pages')
        }
      },
    ...
    
  27. zhuchangfeng commented on Jun 22, 2021

    @zhuchangfeng

    vite 1 verson
    alias: { '@pages': path.resolve(__dirname, './src/pages') }
    vite 2 verson
    resolve:{ alias: [ { find: '@', replacement: resolve('src') , },] },
    crucial step
    yarn add @vitejs/plugin-vue
    yarn upgrade vite@2.3.8

    vite.config.js

    import vue from '@vitejs/plugin-vue'
    import { defineConfig } from 'vite'
    export default defineConfig({
    resolve:{
    alias: [ {
    find: '@',
    replacement: resolve('src') ,
    }]
    }
    })

  28. github-actions commented on Jul 14, 2021

    @github-actions
    Contributor

    This issue has been locked since it has been closed for more than 14 days.

    If you have found a concrete bug or regression related to it, please open a new bug report with a reproduction against the latest Vite version. If you have any other comments you should join the chat at Vite Land or create a new discussion.

  29. locked and limited conversation to collaborators on Jul 14, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions