Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one use a path alias in *.vue component imports in Vite?

Tags:

vue.js

vite

When I work with Vue single file components in Vite I can use a baseUrl and path alias in tsconfig.json to import *.ts files into component files. However, the same does not work with imports of *.vue files because I get a run-time error.

// ts files: works fine
import { FooModel } from "@/models/FooModel"

// vue files: relative path works fine
import { FooComponent } from "./models/FooComponent.vue"

// vue files: path alias gives a run-time error!
import { FooComponent } from "@/models/FooComponent.vue"

There is a similar question on Vite.js Discord Server but it has not been answered yet.

Therefore, my main question is: how can one get the path alias working for single file component imports in Vite?

The subquestion is who does the path resolving for *.vue files in Vite? With Vue CLI this is handled in webpack, if I am not mistaken, so in Vite it is rollup?

like image 698
Neits Avatar asked Nov 22 '25 19:11

Neits


1 Answers

Try this!

// vite.config.js
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src") // map '@' to './src' 
    },
  },
});
like image 60
Nazaire Avatar answered Nov 24 '25 22:11

Nazaire