vue.js - 如何在 Vite 中的 *.vue 组件导入中使用路径别名?

标签 vue.js vite

当我在 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?

最佳答案

试试这个!

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

关于vue.js - 如何在 Vite 中的 *.vue 组件导入中使用路径别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66414059/

相关文章:

typescript - Svelte+TS+Eslint项目,eslint抛出错误: 'console' is not defined

typescript - 部署到heroku期间出现Vite错误

javascript - Vue JS - 使用 innerHTML 呈现的动态创建的组件不能绑定(bind)到事件

javascript - 如何在 vue.js 2 上使用 keyup 禁用点?

javascript - 从列表中更改所选元素的 Vue.js 转换

reactjs - 如何在 TypeScript 中将 Astro 与 WASM 结合使用

javascript - 使用vite将原始图像数据导入到脚本中

javascript - Vue.js(vuex)。重新加载页面时,计算属性返回未定义。 (vuex 中硬编码的对象数据数组)

javascript - 无法在 VUEJS 2 中的 Axios POST 方法中访问 "this"

node.js - 在单独的服务器上发布时,react 和 nodejs 发布问题