方法一:在实际项目中,我们通常可以将src目录设置为@目录,这样引入文件时候可以一目了然而且使用起来非常方便,可以提高我们的开发效率。
[@代表的是src文件夹,这样将来文件过多,找的时候也方便,而且也还有提示]
本文介绍如何在实际项目中使用@作为src目录的别名:
1.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"
]
}
2.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/*"
]
}
}
}