国产探花免费观看_亚洲丰满少妇自慰呻吟_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  }` );             
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 新乐市| 九龙县| 德安县| 嘉鱼县| 阿鲁科尔沁旗| 古浪县| 汉阴县| 江永县| 阿拉善右旗| 阳谷县| 乳源| 西充县| 伊宁县| 辽源市| 电白县| 防城港市| 天柱县| 安新县| 谢通门县| 囊谦县| 沙洋县| 罗源县| 文水县| 视频| 平江县| 丹阳市| 佛坪县| 潞城市| 新野县| 都匀市| 莫力| 淮安市| 郴州市| 邵阳市| 北辰区| 个旧市| 盖州市| 阳原县| 白山市| 武穴市| 万年县|