我们在写vue 的时候需要引入许多的组件, 或者是css样式。 当我们的文件越来越多, 层级也越来越多的时候引入就比较麻烦, 要写很多的’…/…/’,比如这样:import Son from '../.././Son', 为了书写方便, 我们可以给vue路径设置别名,来节省代码的输入次数,提高开发效率

1. 在项目跟路径新建 vue.config.js 文件

在文件里面输入下面的代码:

const path = require('path') // 引入path模块 -> 设置绝对路径
function resolve (dir) { // 声明一个函数,调用函数的时候传入相对路径
  return path.join(__dirname, dir) // return绝对路径
}
module.exports = {
  chainWebpack: (config) => {
    config.resolve.alias
      // .set('路径别名', resolve('vue.config文件的相对路径'))
      .set('api', resolve('./src/api'))
      .set('components', resolve('./src/components'))
      .set('style', resolve('./src/style'))
      .set('utils', resolve('./src/utils'))
      .set('router', resolve('./src/router'))
  }
}

2. 重启编译器 - 修改vue.config.js 后一定要重启

3. 别名的使用

当我们需要引入文件的时候就可以简写了

/*
  引入css样式, css样式表别名的前面需要添加 '~'
  在js中引入也需要添加~
*/
// vue引入
@import '~style/index.less';
// js中引入
import '~style/index.less'

/* 引入组件,  */
import Box from 'components/Box'
Logo

前往低代码交流专区

更多推荐