添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

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

Describe the bug

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

Reproduction

project structure:

vite.config.js
├── 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
  • @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));
      }],
              

    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

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

    @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

    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;
    akauppi, OverlyDramatic, MichaelGitArt, gezhigang1005, Mario34, iandunn, sinnbeck, mariosant, M1chaelTran, henriquehbr, and 7 more reacted with thumbs up emoji OverlyDramatic, MichaelGitArt, simultsop, natalie-o-perret, zhuqunli, Silksofthesoul, lgs821, ahyagoub40, and sadortun reacted with eyes emoji All reactions

    @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?

    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')
      phanmn, a7medev, xland, yolio2003, logustra, spking11, brendonmatos, willedouglas, akrisiun, richard1015, and 21 more reacted with thumbs up emoji
      a7medev, christopher-caldwell, KishiTheMechanic, brendonmatos, willedouglas, iandunn, M1chaelTran, henriquehbr, paulocuambe, Zelgadis87, and 2 more reacted with heart emoji
        All reactions
              

    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.

    Hi, has this been solved?
    I'm using Vite 2.0.0-beta.30 and it's not working.

    I'm using Vue v3.
    I have a template with
    <img :src="urlLogo" />

    computed: { urlLogo() { return this.collapsed ? '@/assets/logoSmall.png' : '/@/assets/logo.png'; } }
    And I keep getting
    GET http://localhost:3000/@/assets/logo.png 404 (Not Found)

    I've tried the alias in the vite.config.js, added the resolvers, nothing works.
    I've tried using:

  • /@/assets/logo.png
  • @/assets/logo.png
  • /@assets/logo.png
  • @assets/logo.png
  • ~/assets/logo.png
  • The only path that works is './src/assets/logo.png', but when I build for production I don't have the /src folder.
    Any suggestion?

    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.

    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()]
      jsmith, AlexeyZelenko, notiv-nt, CyberAP, mismith, 3zzy, akrisiun, robokozo, mindreframer, this-kramer, and 29 more reacted with thumbs up emoji
      yxw007, yuriynekrasov, and lautiamkok reacted with thumbs down emoji
      Arelina and jd150 reacted with hooray emoji
        All reactions
              

    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.

    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.

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

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

    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

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

    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 ?

    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.

    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. ;-)

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

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

    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)

    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:

    But when using root slash:

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

    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

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

    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?

    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 [email protected]

    vite.config.js

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