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)
CodePudding user response:
Try like this:
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
}
}
CodePudding user response:
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).
With this setup '@' alias works fine with simple component importing. But in my case, I was needed in dynamic import with template strings:
If I replace '@' with dot-notation - it works fine. Need your help)
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:
const component = computed(() => {
return defineAsyncComponent(
() => import(`./components/pages/dashboard/${userRole}.vue`)
)
})
- Vite Documentation