Vue 新增不参与打包的接口地址配置文件

 

by:授客 QQ1033553122

 

开发环境

 

Win 10

 

Vue 2.5.2

问题描述

vue工程项目,npm run build webpack方式打包,每次打包后如果需要更改后台接口地址(项目中,接口地址设置成变量,存放在js文件中,需要用到的地方导入),都需要重新打包,比较麻烦,所以,想给项目增加个配置文件,打包后如果要更改接口地址,修改该文件即可。

解决方法

创建config.js

项目根目录/static目录下,创建config.js文件,内容如下:

;(function(env) {

    // 开发环境接口服务器地址

    const dev = {

        API_BASE_URL:"http://localhost:8000"

    }

 

    // 线上环境接口服务器地址

    const prod = {

        API_BASE_URL:"http://10.xxx.xx.xx:8001"

    }

 

    if (env == "dev") {

        return dev

    } else if (env == "prod") {

        return prod

    }

})("dev")

 

 

修改main.js

import axios from "axios"

 

...略

 

let myConfigPath = "/static/config.js"

 

if (process.env.NODE_ENV === "development") {

    myConfigPath = "../static/config.js"

}

 

axios.get(myConfigPath, { headers: { "Cache-Control": "no-cache" } }).then(response => {

  Vue.prototype.$apiBaseURL = eval(response.data).API_BASE_URL

 

  new Vue({

    el: "#app",

    router,

    store, // 注入 store

    components: { App },

    template: "<App/>"

  })

})

 

 

如上,先通过请求,获取config.js文件内容 response.data,然后通过eval(response.data)文件内容当做代码执行,进而获取js中函数返回的内容,即我们需要的配置,并挂载在Vueprototype上,就可以在每个 Vue 的实例中使用。这里把vue创建实例放在获取config.js配置文件之后主要是因为axios异步请求的缘故。

 

注意,这里不能不能使用import,一定要发起网络请求,去请求这个js文件,否则build时,webpack会将此配置文件应当输出的值写死在压缩之后的js中,之后去动手修改dist/static中的配置文件就不起作用了。

 

另外,添加{ headers: { "Cache-Control": "no-cache" } }请求头,防止浏览器从磁盘缓存读取,导致后台更改了配置,前台读取的还是旧的文件。

 

npm run build后,config.js位于dist/static目录下,项目线上环境nginx 静态文件路由关键配置如下:

location / {

            root /opt/TMP/frontend/dist; #这里的dist存放的就是上述打包的路径

...

 

实践表明,使用nginx部署的情况下,myConfigPath 不能设置为 "./static/config.js",只能设置为myConfigPath = "/static/config.js",即配置为绝对路径,否则刷新某些页面的情况下,会请求不到config.js

 

以下为配置myConfigPath "./static/config.js"的情况下,执行二级页面的刷新操作(页面URLhttp://10.1xx.xx.xx/testerView/testCaseManagement,根据我的项目程序设计,此操作会先访问二级路由页面testerView),查看nginx日志,发现如下,请求找不到:

 

 

引用配置

本例中,在自己封装的axios.js中使用该配置

import axios from"axios"

 

import Vue from "vue"

 

...略

 

 

function request(options) {

    return new Promise((resolve, reject) => {

        const instance = axios.create({

        baseURL: Vue.prototype.$apiBaseURL,

 

        headers:config.headers,

        timeout:config.timeout,

        withCredentials:config.withCredentials,

        responseType:config.responseType

    })

    ...略

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/shouke/p/13022272.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程