vitejs / vite

Next generation frontend tooling. It's fast!
http://vite.dev
MIT License
68.43k stars 6.17k forks source link

[suggestion] Alias for "@" to 'src' by default #1536

Closed ghost closed 3 years ago

ghost commented 3 years ago

Describe the solution you'd like Having alias for @ to src by default since we already have it in Vue CLI and Nuxt.

yyx990803 commented 3 years ago

Vite 2 is framework agnostic and won't have default aliases. It's trivial to add this yourself.

ghost commented 3 years ago

I'll leave it for those who might need it


// vite.config.js
import vue from '@vitejs/plugin-vue'
import path from 'path'

/**
 * @type {import('vite').UserConfig}
 */
export default {
  plugins: [vue()],
  alias: {
    '@': path.resolve(__dirname, '/src')
  }
}
qq31311137 commented 3 years ago

@web2033 大哥 这个 alias 在 html 可以生效吗,我升级 vite2 配置了就不生效了

vesper8 commented 3 years ago

I added the code above and it made my @ resolve correctly for its usage inside my main.js, however it is still failing to resolve @ in a bunch of other places such as in my routes and inside my global components declarations

examples:

App.vue

components: {
    RouteTransition: () => import('@/components/RouteTransition'),
  },
Vue.component('Layout', () => import(/* webpackChunkName: "components--layout" */ '@/components/layout/layouts/Layout'));

router.js

  {
    name: 'build',
    path: '/build',
    component: () => import(/* webpackChunkName: "pages--test" */ '@/pages/test/Page-Build'),
    meta: {
      auth,
      title: 'BUILD INFO',
      transition: defaultTransition,
    },
  },

Any idea why it's not resolving in those other files?

ghost commented 3 years ago

Remove those comments /* webpackChunkName: "..." */ they don't work in Vite. Maybe take a look at a starter template on my profile. (jsconfig.json needs some tweaks too)

vesper8 commented 3 years ago

The comments are not the problem, I tried removing them and the error is the same, they would just be treated as a comment in vite so would not interfere

I believe the problem is that '@': path.resolve(__dirname, '/src') makes the alias only work from files that are on the same level as /src, which is why it works from inside my main.js but doesn't work when inside an import from /src/components/file

ghost commented 3 years ago

Add .vue extension to those imports

vesper8 commented 3 years ago

Ah yes.. I was just about to comment and say that that's the problem... with vue-cli the extension is not required.. but now it is.. is there any way to make that backward compatible without having to add the extension everywhere?

ghost commented 3 years ago

Haven't seen it yet.