vite/vue 项目中带有 @ 符号的 src 别名不起作用
我已经使用 Vite CLI 安装了 Vue3/TS 项目,
我的 vite.config.ts 如下所示:
import vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vite'
import path from 'path'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
})
另外,我在 tsconfig.json 中添加了“paths”属性:
{
"compilerOptions": {
...
"baseUrl": "./",
"paths": {
"@/*": ["./src/*", "./dist/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}
通过此设置,“@”别名可以很好地处理简单的组件导入。 但就我而言,我需要使用模板字符串进行动态导入:
<script setup lang="ts">
import { useStore } from '@/store/app'
import { computed, defineAsyncComponent } from 'vue'
const store = useStore()
const userRole = store.getUserRole
const component = computed(() => {
return defineAsyncComponent(
() => import(`@/components/pages/dashboard/${userRole}.vue`)
)
})
</script>
此示例抛出错误:
未捕获(承诺中)类型错误:无法解析模块说明符“@/components/pages/dashboard/admin.vue” 在仪表板.vue:14:54
如果我用点符号替换“@” - 它工作正常。需要你的帮助)
I have installed Vue3/TS project with Vite CLI
My vite.config.ts looks like this:
import vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vite'
import path from 'path'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
})
Also I add 'paths' property inside tsconfig.json:
{
"compilerOptions": {
...
"baseUrl": "./",
"paths": {
"@/*": ["./src/*", "./dist/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}
With this setup '@' alias works fine with simple component importing.
But in my case, I was needed in dynamic import with template strings:
<script setup lang="ts">
import { useStore } from '@/store/app'
import { computed, defineAsyncComponent } from 'vue'
const store = useStore()
const userRole = store.getUserRole
const component = computed(() => {
return defineAsyncComponent(
() => import(`@/components/pages/dashboard/${userRole}.vue`)
)
})
</script>
This sample throw an error:
Uncaught (in promise) TypeError: Failed to resolve module specifier '@/components/pages/dashboard/admin.vue'
at dashboard.vue:14:54
If I replace '@' with dot-notation - it works fine. Need your help)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试这样:
Try like this:
您的别名定义很好,但您缺少有关使用 Vite 导入动态资产的详细信息。我已经在这个答案中解释过(对于Vue,但我们在这里讨论Vite的行为) 。
这是由于汇总限制造成的。所有导入必须相对于导入文件开始,并且导入不应以变量开头。
您必须将别名 (@/) 替换为相对或绝对路径
./components
或/src/components
,就像您已经做的那样:Your alias definition is fine, but you are missing a details about importing dynamic assets with Vite. I already explained it in this answer (for Vue but we are talking about Vite's behavior here).
This is due to Rollup Limitations. All imports must start relative to the importing file and import should not start with a variable.
You have to replace the alias (@/) with relative or absolute path
./components
or/src/components
as you already did: