vue3+vite+ts:使用@符号,实现定位在src目录下。(.vue文件无法使用@,import其他模块)
warning:
这篇文章距离上次修改已过475天,其中的内容可能已经有所变动。
在Vue3+Vite+TypeScript项目中,若要使用@符号来代表src目录,需要在vite.config.ts中配置别名。
- 打开
vite.config.ts或vite.config.js文件。 - 在
configure函数或直接在导出的配置对象中,添加alias配置。
// vite.config.ts 或 vite.config.js
import { defineConfig } from 'vite';
import path from 'path';
export default defineConfig({
// ...
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
// ...
});配置完成后,你就可以在项目中的.vue文件或.ts文件中使用@来代表src目录了。例如:
// 在 .ts 文件中
import MyComponent from '@/components/MyComponent.vue';
// 在 .vue 文件中
<script lang="ts">
import { defineComponent } from 'vue';
import SomeService from '@/services/SomeService';
export default defineComponent({
// ...
});
</script>确保重启Vite开发服务器以使配置生效。
评论已关闭