Vue项目配置@别名全过程
作者:weixin_51204324
这篇文章主要介绍了Vue项目配置@别名全过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
在实际项目中,我们通常可以将 src 目录通过设置别名为 @ 目录,这样引入文件时候可以一目了然而且使用起来非常方便,可以提高我们的开发效率。
@ 代表的是 src 文件夹,这样将来文件过多,找的时候也方便,而且也还有提示。
Webpack + JavaScript 项目配置 @ 别名
在项目新建 vue.config.js,编辑 vue.config.js 内容如下:
const path = require('path')
function resolve(dir) {
return path.join(__dirname, dir)
}
module.exports = {
configureWebpack: {
resolve: {
alias: {
'@': resolve('src')
}
}
}
}新建 jsconfig.json,内容如下:
( @ 在 node_moules 和 dist 文件中不能使用)
# 方法一
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"baseUrl": "./",
"moduleResolution": "node",
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
}
}# 方法二
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": [
"src/*"
]
}
},
"exclude": [
"node_modules",
"dist"
]
}Vite + TypeScript 项目配置 @ 别名
编辑 vite.config.ts 内容如下:
import vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vite'
import { resolve } from 'path'
export default defineConfig({
resolve: {
alias: {
'@': resolve(__dirname, 'src') // 路径别名
},
extensions: ['.js', '.json', '.ts', '.vue'] // 使用路径别名时想要省略的后缀名,可以自己 增减
}
})编辑 tsconfig.json,内容如下:
{
"compilerOptions": {
"baseUrl": ".",
// 用于设置解析非相对模块名称的基本目录,相对模块不会受到baseUrl的影响
"paths": {
// 用于设置模块名到基于baseUrl的路径映射
"@/*": [
"src/*"
]
}
}
}使用方法
重新运行一遍项目即可
import Home from '@/pages/Layout/index.vue'
可能出现的问题
使用 WebStorm + Vue 3 + TypeScript 开发项目时使用 @ 别名
可能会存在以下报错:
Cannot find module ‘@/views/xxx.vue‘ or its corresponding type declarations
意思是说找不到对应的模块“@/views/xxx.vue”或其相应的类型声明,因为 TypeScript 只能解析 .ts 文件,无法解析 .vue 文件
解决方法
查找项目内的 vite-env.d.ts 文件,一开始的时候 vite-env.d.ts 是空文件,我们可以在其中引入如下代码:
declare module '*.vue' {
import { DefineComponent } from "vue"
const component: DefineComponent<{}, {}, any>
export default component
}加入上面的代码后重新运行项目就不再报错了。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
