Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`Vue3 - Vite` project alias src to @ not working

I have installed the project with vue3 - vite importing a component like

import Component from '../../../../components/Component.vue'

i just want to alias the src folder and do

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

this is my vite.config.js

import vue from '@vitejs/plugin-vue'

/**
 * https://vitejs.dev/config/
 * @type {import('vite').UserConfig}
 */
export default {
    plugins: [
        vue({
            template: {
                compilerOptions: {
                    // ...
                }
            }
        })
    ]
}

am i missing something? what else should i do?

like image 865
Oleksii Zelenko Avatar asked Feb 04 '21 10:02

Oleksii Zelenko


3 Answers

In the vite.config.js file write the below code blocks

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  }
})
like image 138
Md. Helal Uddin Avatar answered Nov 09 '22 08:11

Md. Helal Uddin


Update 2022

This solution comes by default from when creating a new project with npm init vue@latest

import { fileURLToPath, URL } from "url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
});

In components use @/:

<script setup>
import HelloWorld from "@/components/HelloWorld.vue";
</script>


This is what worked for me:

import path from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@/': `${path.resolve(__dirname, 'src')}/`
    }
  }
})

Then in components:

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld msg="Hello Vue 3 + Vite" />
</template>

<script>
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>
like image 74
Roland Avatar answered Nov 09 '22 07:11

Roland


Vue 3 Vite TypeScript

vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

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

To remove warnings and add hint to download with @/

tsconfig.json

{
  "compilerOptions": {
    ...
    "paths": {
      "@/*": ["./src/*", "./dist/*"]
    }
  }
}
like image 20
Mises Avatar answered Nov 09 '22 08:11

Mises