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

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

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 2
  • Comments: 49 (12 by maintainers)

Most upvoted comments

import vue from '@vitejs/plugin-vue'

export default {
  alias: {
    '/@': path.resolve(__dirname, './src')
  },
  plugins: [vue()]
}

does not work

I think you are just missing the const path = require('path'); part. Make sure to also add the leading “/” when importing components in the Vue script section, i.e.: import Container from "/@/views/Container.vue";

Edit: I also used path.resolve(__dirname, 'src') instead of path.resolve(__dirname, './src') but that should not matter.

Edit2: You could also use the find and replace option to alias the @, i.e.:

const path = require('path');
import vue from '@vitejs/plugin-vue'

export default {
    alias: [
        {find: "@", replacement: path.resolve(__dirname, 'src')}
    ],
    optimizeDeps: {
        include: [
            "javascript-time-ago/locale/de"
        ],
    },
    plugins: [vue()]
};

then again you don’t need the leading slash when importing.

Edit 3: Since vite 2.0.1 introduces the resolve syntax, use:

const path = require('path');
import vue from '@vitejs/plugin-vue'

export default {
    resolve: {
        alias: [
            {find: "@", replacement: path.resolve(__dirname, 'src')}
        ],
        optimizeDeps: {
            include: [
                "javascript-time-ago/locale/de"
            ],
        },
    },
    plugins: [vue()]
};

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')
  }
}

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.

You have to import as /@/xxx, it cannot start with @ because that’s considered a package.

Note Vite is not a bundler - it’s a dev server. Any request not starting with / or . is considered a module dependency request. All other requests must be valid HTTP requests (start with / or .).

This also means you can NOT directly import from fs paths like in webpack:

import foo from '/some/fs/path/foo.js'

This doesn’t make sense in Vite. So anything starting with / is a request from the root where the server is serving.

// 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' },
    ]
  }
})

Having trouble with aliases here after upgrading to 2.0.1.

vite.config.ts

import path from 'path'
import { defineConfig } from 'vite'

export default defineConfig({
  resolve: {
    alias: [
      {
        find: '@/',
        replacement: path.resolve(__dirname, './src')
      }
    ]
  },
  optimizeDeps: {
    include: ['lodash']
  }
})

And then it errors in places such as:

import Nav from '@/components/Nav.vue', component: () => import('@/views/About.vue')

The error message says the plugin "vite:dep-scan" didn't set a resolve directory, but I can’t find anything related to vite:dep-scan anywhere on the internet… 🤔

I’ve tried the various @rollup/plugin-alias config options syntax from (here) as well as with and without the defineConfig() wrapper - all no luck and generating the same error message.

Heads up I was porting an app and /@/xxx aliasing working for all code but the assets did not work.

// 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

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. 😉

@ndom91 Does it work when you delete the / from find: '@/'?

import vue from '@vitejs/plugin-vue'

export default {
  alias: {
    '/@': path.resolve(__dirname, './src')
  },
  plugins: [vue()]
}

does not work

The Asset Handling section of the vite documentation is probably what you’re looking for. Your logic is flawed (I think) since vite doesn’t get the chance to transform /@/assets/logoSmall.png or /@/assets/logo.png. I haven’t used vite in a few months but I think something like this might work:

import logo from '/@/assets/logo.png'
import logoSmall from '/@/assets/logoSmall.png'

// ...
computed: { urlLogo() { return this.collapsed ? smallLogo : logo; } }
// ...

This solution assumes that you have the alias correctly configured. Make sure to read through Alias Behavior Change.

source config image

image I use vite v2.0.5, change to this run is ok

With the resolve.alias config in 2.0.1, you can use @/ directy instead of /@/

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') },
    ],
  },
})

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

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/*"]
    },

It makes sense to post a comment with a clear solution for others to find, that is not a problem 👍🏼

But asking questions against a closed bug report is not helpful because the context refers to an older version of Vite, and it doesn’t allow proper tracking of concrete bugs in newer versions. Issues are not intended to be used for discussions, we have better platforms for that with GitHub Discussion and Vite Land. If a good solution to something that is not clear in this issue is identified there, it is a good idea to link it from here for later reference.

Thanks @jsmith,

Your solution worked well and I learnt something new.

Thanks