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_moulesdist 文件中不能使用)

# 方法一

{
  "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
}

加入上面的代码后重新运行项目就不再报错了。

参考文章

Vue项目中怎么配置在src文件下@别名
vue3/vue2 项目配置 别名 @
Cannot find module ‘../views/HomeView.vue‘ or its corresponding type declarations.ts
webstorm vue3+ts报错:Cannot find module ‘@/views/xxx.vue‘ or its corresponding type declarations

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注