在vue项目中动态路径使用@路径而不是用./

vue使用@路径引入,这个在项目中很常见;

项目中使用引入文件有时候路径比较深,需要使用"../../../xx.js"这种类似的路劲引入,这种方式比较笨,可以使用webpack的别名alias配置来解决。

首先,先确定项目中是否有path模块:

如果没有path模块需要先安装path

npm  install  path  --save
1
(1)vue-cli1,vue-cli2搭建的项目
以下为vue.config.js配置

const path = require("path");
function resolve(dir) {
  return path.join(__dirname, dir);
}
 
module.exports = {
  chainWebpack: config => {
    config.resolve.alias
      .set("@", resolve("src"))
      .set("assets", resolve("src/assets"))
      .set("components", resolve("src/components"))
      .set("base", resolve("baseConfig"))
      .set("public", resolve("public"));
  },
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(2)webpack3,4的写法

这个@是在 webpack.base.conf.js 文件里配置的,找到下面这段话

 resolve: {   
  extensions: ['.js', '.vue', '.json'],    
  alias: {     
   'vue$': 'vue/dist/胜利ue.esm.js',   
   '@': resolve('src'),   
    } 
 },
1
2
3
4
5
6
7
(3)vue-cli3搭建的项目
以下为vue.config.js配置

  publicPath: '/asset/baigei2020/alipay_act',
  outputDir: '../../../public/asset/baigei2020/alipay_act',
  assetsDir: 'static',
  productionSourceMap: false,
  devServer: {
    port: 3002,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      '/api': {
        target: 'http://mayouchen.test.com/',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        },
        cookieDomainRewrite: {
          '*': 'localhost'
        }
      }
    }
    //after: require('./mock/mock-server.js')
  },
  configureWebpack: {
    resolve: {
      extensions: ['.js', '.vue', '.json'],
      alias: {
        '@': resolve('src'),
        '~': process.cwd(),
        public: resolve('public'),
        components: resolve('src/components'),
        util: resolve('src/utils'),
        store: resolve('src/store'),
        router: resolve('src/router')
      }
    }
  },
  transpileDependencies: [
    '_ant-design-vue@1.3.10@ant-design-vue',
    'ant-design-vue'
  ],
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
根据上面配置实例演示:

————————————————
版权声明:本文为CSDN博主「马优晨」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_24147051/article/details/106557242

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值