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

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

 

by:授客 QQ1033553122webpack

 

开发环境

 

Win 10ios

 

Vue 2.5.2nginx

问题描述

vue工程项目,npm run build webpack方式打包,每次打包后若是须要更改后台接口地址(项目中,接口地址设置成变量,存放在js文件中,须要用到的地方导入),都须要从新打包,比较麻烦,因此,想给项目增长个配置文件,打包后若是要更改接口地址,修改该文件便可。web

解决方法

建立config.js

项目根目录/static目录下,建立config.js文件,内容以下:npm

;(function(env) {axios

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

    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

    })

    ...略

相关文章
相关标签/搜索