vue项目多人协作避免target冲突

220 阅读1分钟

先看文件夹目录:重点是config文件夹下的配置,.gitignore,vue.config.js文件

要把vue项目跟后台对接接口api单独提出来,首先对vue.config.js进行改造:把proxy单独提出来

vue.config.js:

'use strict'
const path = require('path')
const proxy = require('./config/proxy/index.js')//这一行是重点

function resolve(dir) {
  return path.join(__dirname, dir)
}
const port = 9527 // 端口配置
module.exports = {
  publicPath: '/',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    port: port,
    open: false,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: proxy  //这一行是重点
  }
}

config/proxy/index.js:

const fs = require('fs')
const getFileUrl = fileName => `./config/proxy/${fileName}`
const LOCAL_FILE_NAME = 'proxy.dev.local.js'//本地配置文件名称
// 本地的开发环境变量配置文件,属于gitignore
const localFileUrl = getFileUrl(LOCAL_FILE_NAME)

// 默认请求
const apiHost = {
  rewrite: process.env.VUE_APP_BASE_API,
  target: 'http://192.xxx.xxx.xxx:8080'
}
let proxyList = []

function getProxies(PROXY_LIST = []) {
  const res = {}
  PROXY_LIST.forEach(proxyItem => {
    let source = proxyItem.rewrite
    if (source && source.charAt(source.length - 1) === '/') {
      source = source.substring(0, source.length - 1)
    }
    res[source] = {
      target: proxyItem.target,
      changeOrigin: true,
      pathRewrite: {
        ['^' + source]: ''
      }
    }
  })
  return res
}
// 核心代码,通过模板(proxy.dev.tpl)创建自己本地的配置文件
// 本地的开发配置文件不存在,则创建并初始化为空的
if (!fs.existsSync(localFileUrl)) {
  fs.copyFile(getFileUrl('proxy.dev.tpl'), localFileUrl, err => {
    const isFail = !!err

    console.warn(`\n[${isFail ? 'warn' : 'info'}]config/proxy.js: 创建${localFileUrl}${isFail ? `失败,${err.stack}` : '成功'}`)
  })
  proxyList.push(apiHost)
} else {
  // 当存在时获取proxy配置
  proxyList = require(`./${LOCAL_FILE_NAME}`)
}

const proxy = getProxies(proxyList)

module.exports = proxy

config/proxy/proxy.dev.tpl: 模板:

const proxyList = [
  {
    rewrite: process.env.VUE_APP_BASE_API,
    target: 'http://192.xxx.xxx.xxx:8080'
  }
]
module.exports = proxyList


第一次运行,会创建 proxy.dev.local.js 的文件,该文件是自己本地的配置文件,每个人拥有自己的配置文件,该文件不会被提交,不会有代码冲突

.gitignore文件:提交的时候不提交自己本地使用的配置文件

在这里插入图片描述