Vue为文件目录设置别名

cli-4的脚手架配置

因为组件的引用,经常会遇到import * from  '../../../components/common/***.vue‘这样的引入格式,太复杂了,所以可以在vue里面配置路径别名

首先在最外层,和package.json同级目录里面新建一个vue.config.js作为扩展配置。

我的目录结构:

vue.config.js:关键代码:黑体加粗部分

const path = require('path');
module.exports = {
  outputDir: 'docs',
  configureWebpack: {
    devServer: {
      open: true,
      // 代理
      proxy: {
        '/netease-api': {
          target: 'http://localhost:3000',
          pathRewrite: {
            '/netease-api': ''
          },
          changeOrigin: true,
          secure: false
        }
      }
    },
    resolve: {
      // 别名
      alias: {
        '@': path.resolve(__dirname, './src'),
        assets: path.resolve(__dirname, './src/assets'),
        components: path.resolve(__dirname, './src/components'),
        style: path.resolve(__dirname, './src/style'),
        utils: path.resolve(__dirname, './src/utils')
      }
    }
  },
  css: {
    loaderOptions: {
      sass: {
        prependData: `
          @import "~@/style/variables.scss";
          @import "~@/style/mixin.scss";
        `
      }
    }
  }
};

引用的时候就可以这样写了:

@代表 src 目录

比如我的路由文件:

import Vue from 'vue';
import VueRouter from 'vue-router';
import Index from '@/layout/index.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Index',
    component: Index
  }
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
];

const router = new VueRouter({
  routes
});

export default router;

原文地址:https://www.cnblogs.com/hahahakc/p/13093717.html