【问题标题】:How can one use a path alias in *.vue component imports in Vite?如何在 Vite 的 *.vue 组件导入中使用路径别名?
【发布时间】:2021-05-30 12:01:49
【问题描述】:

当我在 Vite 中使用 Vue 单文件组件时,我可以在 tsconfig.json 中使用 baseUrlpath 别名来导入 *. ts 文件转换为组件文件。但是,这同样不适用于 *.vue 文件的导入,因为我遇到了运行时错误。

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

Vite.js Discord Server上也有类似的问题,但还没有回答。

因此,我的主要问题是:如何让路径别名适用于 Vite 中的单个文件组件导入?

子问题是谁在 Vite 中解析 *.vue 文件的路径?使用Vue CLI,这是在webpack中处理的,如果我没记错的话,那么在Vite中它是rollup?

【问题讨论】:

    标签: vue.js vite


    【解决方案1】:

    试试这个!

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

    【讨论】:

      猜你喜欢
      • 2022-10-23
      • 2021-02-06
      • 1970-01-01
      • 2016-04-28
      • 2023-01-20
      • 2016-11-30
      • 2020-11-28
      • 2019-03-06
      • 2022-01-21
      相关资源
      最近更新 更多