vue中配置alias

配置 alias

在 vue 中有时经常会因为引入文件的相对路径过长,这时可以在 vue.config.js 中配置一下别名。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const path = require('path')

function resolve(dir) {
return path.join(__dirname, dir)
}

module.exports = {
chainWebpack(config) {
config.resolve.alias
.set('components', resolve('src/components'))
.set('common', resolve('src/common'))
.set('api', resolve('src/api'))
}
}

上面的代码配置了 src 目录下的 components、common 和 api 这三个文件夹。

在 css 中引入

这里注意前面要加一个 ~

1
2
@import "~common/stylus/mixin"
@import "~common/stylus/variable"

在 JavaScript 中引入

1
import SupportIco from 'components/support-ico/support-ico'
1
2
// api 目录下有 index.js
import { getSeller } from 'api'

源码参考

在 /node_modules/@vue/cli-service/lib/config/base.js 中找到了下面的代码,也解释了 @ 是 src 目录的别名

1
2
3
4
5
6
7
8
9
10
11
api.chainWebpack(webpackConfig => {
webpackConfig.resolve
.alias
.set('@', api.resolve('src'))
.set(
'vue$',
options.runtimeCompiler
? 'vue/dist/vue.esm.js'
: 'vue/dist/vue.runtime.esm.js'
)
}