国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

vue 項目打包通過命令修改 vue-router 模式 修改 API 接口前綴

2024-05-06 15:33:27
字體:
來源:轉載
供稿:網友

需求說明:

在開發 vue 項目的過程中遇到的需求是要把 api 接口前綴暴露在命令行,通過 npm run build apiUrl 即可修改接口入口,用于從 docker 部署到不同的測試服務器上,其次是路由模式的問題,部署到測試服務器上的需要是 history 模式,但是產品是用 electron + vue 開發的桌面應用,electron 硬性要求 vue-router 的路由模式是 hash 模式,所以命令行需新增一個配置項 mode ,mode 可選值有 history 、hash

最終結果:

npm run build '' hash  --->  使用源碼中寫死的 api 入口 ,vue-router 模式是 hash 模式

npm run build https://192.168.166.101:8444 history  --->  使用 https://192.168.166.101:8444 作為 api 入口,vue-router 模式是 history 模式

實現:

1.新建 base/config.js 用于存放從 webpack.prod.conf.js 里寫入的數據

2.新建 base/index.js 用于將從 base/config.js 里導出的 config 掛載在 Vue 原型的 $config 對象上

3.新建 build/apiConfig.js 用于封裝 fs-extra 對文件的讀寫

4.在 webpack.prod.conf.js 將命令行中敲入的命令寫入 base/config.js 里

5.在 main.js 中將 base/index.js 拋出的 install 掛載到 Vue 上

6.在 Login.vue 和 router/index.js 里引入 this.$config.host 以及 base/config.js 即可

關鍵代碼:

2.新建 base/index.js 用于將從 base/config.js 里導出的 config 掛載在 Vue 原型的 $config 對象上

// 將 config 封裝成插件 // example this.$config // 導入所有接口 import config from './config'; const install = Vue => {   if(install.installed)     return;   install.installed = true;   Object.defineProperties(Vue.prototype, {     // 此處掛載在 Vue 原型的 $config 對象上     $config:{       get(){         return config;       }     }   }) } export default install; 

3.新建 build/apiConfig.js 用于封裝 fs-extra 對文件的讀寫

const fs = require("fs-extra"); const path = require("path"); var _path = path.join(__dirname, "../src/base/host.js"); if (!fs.pathExistsSync(_path)) {  // 如果不存在路徑  fs.mkdirpSync(_path); // 就創建 } module.exports = {  read: function() {   let filesData = fs.readFileSync(_path, "utf-8", function(e, data) {    if (e) throw e;    return data;   });   return filesData;  },  write: function(writeStr) {   fs.open(_path, "w", function(e, fd) {    if (e) throw e;    fs.write(fd, writeStr, 0, "utf8", function(e) {     if (e) throw e;     fs.closeSync(fd);    });   });  } }; 

4.在 webpack.prod.conf.js 將命令行中敲入的命令寫入 base/config.js 里  

const apiConfig = require('./apiConfig'); apiConfig.read(); apiConfig.write(  `export const host = '${process.argv[2]}';   export const mode = '${process.argv[3]}';  // 默認全部倒出  // 根絕需要進行   export default {  host,  mode  }` );             
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 庆云县| 星座| 铜川市| 阿拉尔市| 南充市| 庄河市| 吉木乃县| 广河县| 乌鲁木齐县| 恩平市| 天津市| 嵩明县| 柘荣县| 鲁山县| 曲松县| 潼关县| 望江县| 浮梁县| 安泽县| 汤阴县| 睢宁县| 凤城市| 泗阳县| 台中县| 延川县| 赤城县| 霍城县| 平武县| 泾阳县| 铜川市| 霍邱县| 霍林郭勒市| 达州市| 威宁| 定南县| 托克逊县| 崇礼县| 白玉县| 波密县| 石屏县| 海淀区|