GitBucket
4.6.0
Toggle navigation
Sign in
Files
Branches
1
Tags
Issues
Pull Requests
Labels
Milestones
Wiki
08335
/
hivui-platform-template
hivui平台项目模板
Browse code
Jenkins commit
master
1 parent
b1e441d
commit
ff710c2b97f95def4076a660da015f1f2937f063
12896
authored
on 11 Apr 2023
Showing
2 changed files
project/hivuiMain/views/layout/index.vue
vite-plugin/vite-plugin-func.js
Ignore Space
Show notes
View
project/hivuiMain/views/layout/index.vue
<template> <div v-if="layout == 'level'" class="pl-page" :class="isFullscreen?'showTab':''"> <div style="height: 1px;width: 100%;position: absolute;left: 0;top: 0;z-index: 10000;" @mouseenter="showTab"></div> <Header v-show="!isFullscreen" :hasTitle="hasTitle" :logoWidth="logoWidth" ref="Header" style="box-shadow: 0 5px 7px rgba(221,221,221,0.5);z-index:10"></Header> <!-- <Navbar></Navbar> --> <Sidebar ref="Sidebar" :hasTitle="hasTitle" :sideWidth="sideWidth" :totop="totop" style="z-index: 11"></Sidebar> <Main ref="Main" @onFullScreen="handleFullScreen" :style="{left:toleft, top:totop+'px'}"></Main> </div> <div v-else class="pl-page" :class="isFullscreen?'showTab':''"> <div style="height: 1px;width: 100%;position: absolute;left: 0;top: 0;z-index: 10000;" @mouseenter="showTab"></div> <Header ref="Header" :logoWidth="logoWidth" v-show="!isFullscreen"></Header> <Navbar ref="Navbar" v-show="!isFullscreen"></Navbar> <Sidebar ref="Sidebar" v-show="hasQuickNav&&!isFullscreen"></Sidebar> <Main ref="Main" @onFullScreen="handleFullScreen" :style="{left:hasQuickNav?71:0}"></Main> </div> </template> <script> import {baseURL,codeProjectName,requestUrl} from '@main/config' import {getMenus} from '@main/api/menu' import {checkUrl} from '@main/utils/index' import {Header,Navbar,Sidebar,Main} from "./components" import screenfull from 'screenfull' // import { setTimeout } from 'timers'; export default { components:{ Header,Navbar,Sidebar,Main }, provide(){ let me=this; return { addTab(item){ // url,title,uid,callback,nearest // this.addTab(item);//inject 提供的方法只能 传一个参数 me.addTab(item.resUrl,item.name,item.resId,item.callback,item.nearest,item.openType); // me.addTab(url,title,uid,callback,nearest); }, showTab(){ // console.log('layout index vue : showTab') me.showTab(); }, hideTab(){ // console.log('layout index vue : hideTab') me.hideTab(); } } }, data(){ return { hasTitle: true, toleft: window.__sysConfig.isMenuWordwrap?(window.__sysConfig.leftMenuWidth?(window.__sysConfig.leftMenuWidth+"px"):'141px'):'71px', sideWidth: window.__sysConfig.isMenuWordwrap?(window.__sysConfig.leftMenuWidth?(window.__sysConfig.leftMenuWidth+"px"):'140px'):'70px', logoWidth:'140px', totop: 50, isFullscreen: false, top: '', left: '', mainTop: '', navTop: '', timeout: null, sysConfig: this.$store.state.app.config, } }, computed:{ hasQuickNav(){ return this.$store.getters.navs.length; }, layout(){ return window.localStorage.getItem('layout'); }, isTitle(){ return this.hasTitle; } }, methods:{ addTab(url,title,uid,callback,nearest,openType){ console.log('layout addTab :',baseURL,codeProjectName,url); let __url=url; if(!checkUrl(url)){ //根据setting配置是否带e5 __url=(window._global?location.origin:window.HIVUI_SETTING.serverUrl)+url; } if(openType==2){//弹窗 this.$refs.Main.menuOpenList.push({ title:title, url:__url, uid:uid, }); }else if(openType==3){//浏览器标签打开 window.open(__url,"_blank"); }else{//主界面框架标签打开 window.Sys.addTab(__url,title,uid,callback,nearest); } }, hideTitle(name){ this.hasTitle = name; this.toleft = name?'71px':'49px'; this.sideWidth = name?'70px':'48px' }, /** * 是否全屏并按键ESC键的方法 */ checkFull() { var isFull = document.fullscreenEnabled || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled // to fix : false || undefined == undefined if (isFull === undefined) { isFull = false } return isFull }, handleFullScreen(){ screenfull.toggle() }, onchange(){ // console.log(this.isFullscreen) if(this.isFullscreen==true){ // this.$refs.Main.isFullscreen = true this.$refs.Sidebar.$el.style.top=0 this.$refs.Sidebar.$el.style.left=0 this.$refs.Main.$el.style.top=0 this.$refs.Main.$el.style.left=0 // console.log('222',this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style) this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='none' this.$refs.Sidebar.$el.style.display = 'none' this.$refs.Main.$refs['cmp-tabs'].resize() }else{ // console.log(222) // console.log('top',this.top) this.$refs['Sidebar'].$el.style.top=this.mainTop+this.navTop+'px' this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='block' this.$refs.Sidebar.$el.style.display = 'block' if(window.localStorage.getItem('layout') === 'level'){ this.$refs['Main'].$el.style.top=this.navTop+'px' this.$refs['Main'].$el.style.left=this.left }else{ this.$refs['Main'].$el.style.top=this.mainTop+this.navTop+'px' this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.top=this.mainTop+this.navTop+'px' this.$refs['Main'].$el.style.left=this.left this.$refs['Navbar'].$el.style.top=this.navTop+'px' this.$refs.Navbar.$el.style.display='block' } this.$refs.Main.$refs['cmp-tabs'].resize() } }, showTab(){ if(this.isFullscreen){ clearTimeout(this.timeout); this.timeout = setTimeout(()=>{ this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='block' this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.top=this.mainTop+'px' // this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.top='50px' // console.log(this.$refs.Main.$el.style.top) if(window.localStorage.getItem('layout') === 'level'){ this.$refs.Sidebar.$el.style.display = 'block' this.$refs.Sidebar.$el.style.top = '39px' }else{ // this.$refs.Sidebar.$el.style.display = 'block' this.$refs.Navbar.$el.style.display='none'; this.$refs.Navbar.$el.style.top=0 this.$refs.Navbar.$el.style.display='block' } // this.$refs.Main.$refs['cmp-tabs'].resize() },0); } }, hideTab(){ if(this.isFullscreen){ clearTimeout(this.timeout); this.timeout = setTimeout(()=>{ this.$refs.Main.$el.style.top=0 this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='none' if(window.localStorage.getItem('layout') === 'level'){ this.$refs.Sidebar.$el.style.display = 'none' }else{ this.$refs.Navbar.$el.style.display='none' } // this.$refs.Main.$refs['cmp-tabs'].resize() },0); } }, KeyDown(event) { if (event.keyCode === 122) { event.returnValue = false; this.handleFullScreen(); } } }, created(){ //单页模式强制左右布局 if(this.sysConfig.layout){ if(this.sysConfig.layout=="top"){ window.localStorage.setItem('layout','vertical'); }else if(this.sysConfig.layout=="left"){ window.localStorage.setItem('layout','level'); } } }, mounted(){ this.navTop = this.$refs.Header.$el.offsetHeight this.left = this.$refs.Main.$el.style.left console.log('left', this.isFullscreen) if(window.localStorage.getItem('layout') === 'level'){ this.totop = this.$refs.Header.$el.offsetHeight || 50 }else{ this.mainTop = this.$refs.Navbar.$el.offsetHeight // console.log('mainTop', this.mainTop) } window.onresize = () => { // 全屏下监控是否按键了ESC if (!this.checkFull()) { // 全屏下按键esc后要执行的动作 this.isFullscreen = false } this.isFullscreen=screenfull.isFullscreen this.onchange() }, window.addEventListener("keydown", this.KeyDown, true);//监听按键事件 } } </script> <style lang="less" scoped> .menuOpenDialog{ ::v-deep .el-dialog__body{ padding-top:0; } } </style>
<template> <div v-if="layout == 'level'" class="pl-page" :class="isFullscreen?'showTab':''"> <div style="height: 1px;width: 100%;position: absolute;left: 0;top: 0;z-index: 10000;" @mouseenter="showTab"></div> <Header v-show="!isFullscreen" :hasTitle="hasTitle" :logoWidth="logoWidth" ref="Header" style="box-shadow: 0 5px 7px rgba(221,221,221,0.5);z-index:10"></Header> <!-- <Navbar></Navbar> --> <Sidebar ref="Sidebar" :hasTitle="hasTitle" :sideWidth="sideWidth" :totop="totop" style="z-index: 11"></Sidebar> <Main ref="Main" @onFullScreen="handleFullScreen" :style="{left:toleft, top:totop+'px'}"></Main> </div> <div v-else class="pl-page" :class="isFullscreen?'showTab':''"> <div style="height: 1px;width: 100%;position: absolute;left: 0;top: 0;z-index: 10000;" @mouseenter="showTab"></div> <Header ref="Header" :logoWidth="logoWidth" v-show="!isFullscreen"></Header> <Navbar ref="Navbar" v-show="!isFullscreen"></Navbar> <Sidebar ref="Sidebar" v-show="hasQuickNav&&!isFullscreen"></Sidebar> <Main ref="Main" @onFullScreen="handleFullScreen" :style="{left:hasQuickNav?71:0}"></Main> </div> </template> <script> import {baseURL,codeProjectName,requestUrl} from '@main/config' import {getMenus} from '@main/api/menu' import {checkUrl} from '@main/utils/index' import {Header,Navbar,Sidebar,Main} from "./components" import screenfull from 'screenfull' // import { setTimeout } from 'timers'; export default { components:{ Header,Navbar,Sidebar,Main }, provide(){ let me=this; return { addTab(item){ // url,title,uid,callback,nearest // this.addTab(item);//inject 提供的方法只能 传一个参数 me.addTab(item.resUrl,item.name,item.resId,item.callback,item.nearest,item.openType); // me.addTab(url,title,uid,callback,nearest); }, showTab(){ // console.log('layout index vue : showTab') me.showTab(); }, hideTab(){ // console.log('layout index vue : hideTab') me.hideTab(); } } }, data(){ return { hasTitle: true, toleft: window.__sysConfig.isMenuWordwrap?'141px':'71px', sideWidth: window.__sysConfig.isMenuWordwrap?'140px':'70px', logoWidth:'140px', totop: 50, isFullscreen: false, top: '', left: '', mainTop: '', navTop: '', timeout: null, sysConfig: this.$store.state.app.config, } }, computed:{ hasQuickNav(){ return this.$store.getters.navs.length; }, layout(){ return window.localStorage.getItem('layout'); }, isTitle(){ return this.hasTitle; } }, methods:{ addTab(url,title,uid,callback,nearest,openType){ console.log('layout addTab :',baseURL,codeProjectName,url); let __url=url; if(!checkUrl(url)){ //根据setting配置是否带e5 __url=(window._global?location.origin:window.HIVUI_SETTING.serverUrl)+url; } if(openType==2){//弹窗 this.$refs.Main.menuOpenList.push({ title:title, url:__url, uid:uid, }); }else if(openType==3){//浏览器标签打开 window.open(__url,"_blank"); }else{//主界面框架标签打开 window.Sys.addTab(__url,title,uid,callback,nearest); } }, hideTitle(name){ this.hasTitle = name; this.toleft = name?'71px':'49px'; this.sideWidth = name?'70px':'48px' }, /** * 是否全屏并按键ESC键的方法 */ checkFull() { var isFull = document.fullscreenEnabled || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled // to fix : false || undefined == undefined if (isFull === undefined) { isFull = false } return isFull }, handleFullScreen(){ screenfull.toggle() }, onchange(){ // console.log(this.isFullscreen) if(this.isFullscreen==true){ // this.$refs.Main.isFullscreen = true this.$refs.Sidebar.$el.style.top=0 this.$refs.Sidebar.$el.style.left=0 this.$refs.Main.$el.style.top=0 this.$refs.Main.$el.style.left=0 // console.log('222',this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style) this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='none' this.$refs.Sidebar.$el.style.display = 'none' this.$refs.Main.$refs['cmp-tabs'].resize() }else{ // console.log(222) // console.log('top',this.top) this.$refs['Sidebar'].$el.style.top=this.mainTop+this.navTop+'px' this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='block' this.$refs.Sidebar.$el.style.display = 'block' if(window.localStorage.getItem('layout') === 'level'){ this.$refs['Main'].$el.style.top=this.navTop+'px' this.$refs['Main'].$el.style.left=this.left }else{ this.$refs['Main'].$el.style.top=this.mainTop+this.navTop+'px' this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.top=this.mainTop+this.navTop+'px' this.$refs['Main'].$el.style.left=this.left this.$refs['Navbar'].$el.style.top=this.navTop+'px' this.$refs.Navbar.$el.style.display='block' } this.$refs.Main.$refs['cmp-tabs'].resize() } }, showTab(){ if(this.isFullscreen){ clearTimeout(this.timeout); this.timeout = setTimeout(()=>{ this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='block' this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.top=this.mainTop+'px' // this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.top='50px' // console.log(this.$refs.Main.$el.style.top) if(window.localStorage.getItem('layout') === 'level'){ this.$refs.Sidebar.$el.style.display = 'block' this.$refs.Sidebar.$el.style.top = '39px' }else{ // this.$refs.Sidebar.$el.style.display = 'block' this.$refs.Navbar.$el.style.display='none'; this.$refs.Navbar.$el.style.top=0 this.$refs.Navbar.$el.style.display='block' } // this.$refs.Main.$refs['cmp-tabs'].resize() },0); } }, hideTab(){ if(this.isFullscreen){ clearTimeout(this.timeout); this.timeout = setTimeout(()=>{ this.$refs.Main.$el.style.top=0 this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='none' if(window.localStorage.getItem('layout') === 'level'){ this.$refs.Sidebar.$el.style.display = 'none' }else{ this.$refs.Navbar.$el.style.display='none' } // this.$refs.Main.$refs['cmp-tabs'].resize() },0); } }, KeyDown(event) { if (event.keyCode === 122) { event.returnValue = false; this.handleFullScreen(); } } }, created(){ //单页模式强制左右布局 if(this.sysConfig.layout){ if(this.sysConfig.layout=="top"){ window.localStorage.setItem('layout','vertical'); }else if(this.sysConfig.layout=="left"){ window.localStorage.setItem('layout','level'); } } }, mounted(){ this.navTop = this.$refs.Header.$el.offsetHeight this.left = this.$refs.Main.$el.style.left console.log('left', this.isFullscreen) if(window.localStorage.getItem('layout') === 'level'){ this.totop = this.$refs.Header.$el.offsetHeight || 50 }else{ this.mainTop = this.$refs.Navbar.$el.offsetHeight // console.log('mainTop', this.mainTop) } window.onresize = () => { // 全屏下监控是否按键了ESC if (!this.checkFull()) { // 全屏下按键esc后要执行的动作 this.isFullscreen = false } this.isFullscreen=screenfull.isFullscreen this.onchange() }, window.addEventListener("keydown", this.KeyDown, true);//监听按键事件 } } </script> <style lang="less" scoped> .menuOpenDialog{ ::v-deep .el-dialog__body{ padding-top:0; } } </style>
Ignore Space
Show notes
View
vite-plugin/vite-plugin-func.js
var querystring = require('querystring'); var url = require('url'); const fs = require('fs') var https = require('https'); var request = require('request'); var ejs = require('ejs'); function myPlugin(rawOptions) { let projectName = process.env.VITE_APP_PN.split("/")[0]; var previewPath = `${projectName}/setting/studio/preview.json` var setting try { let settingContent = fs.readFileSync(previewPath, { encoding: 'utf8' }); setting = JSON.parse(settingContent) } catch (e) { console.log("preview数据有错!") } var VITE_APP_BASE_API, VITE_APP_SERVER; if (setting) { VITE_APP_BASE_API = (setting.server || {}).VITE_APP_BASE_API || process.env.VITE_APP_BASE_API; VITE_APP_SERVER = (setting.server || {}).VITE_APP_SERVER || process.env.VITE_APP_SERVER; } else { VITE_APP_BASE_API = process.env.VITE_APP_BASE_API; VITE_APP_SERVER = process.env.VITE_APP_SERVER; } const options = { isProduction: process.env.NODE_ENV === 'production', ...rawOptions, VITE_APP_BASE_API: VITE_APP_BASE_API, VITE_APP_SERVER: VITE_APP_SERVER, root: process.cwd(), }; let postData; let config; return { name: 'vite-plugin-func', // 必须的,将会显示在 warning 和 error 中 configResolved(resolvedConfig) { // 存储最终解析的配置 config = resolvedConfig }, configureServer(server) { server.middlewares.use((req, res, next) => { var Cookies = {}; if (req.headers.cookie != null) { req.headers.cookie.split(';').forEach(l => { var parts = l.split('='); Cookies[parts[0].trim()] = (parts[1] || '').trim(); }); } var param = req._parsedUrl.query; var result = {}; if (param) { let values = param.split("&"); for (let i = 0; i < values.length; i++) { const element = values[i]; let _val = element.split("="); result[_val[0]] = _val[1]; } } function isFlow(type) { return type.endsWith(".flow") || type.endsWith(".flowc"); } // 接口 function isInfc(type) { return type.endsWith(".infc") } function isFunc(type) { return type.endsWith(".func") } function isHtml(type) { return type.endsWith(".html") } // 渲染页面 function renderHtml(pcform, isGuest, body) { let content; try { content = fs.readFileSync(pcform, { encoding: 'utf8' }) } catch (e) { res.writeHead(404, { "Content-Type": "application/json;charset=UTF-8" }); res.end("pcform:" + pcform + "文件异常!"); return; } const statusCode = 200; if (!body) throw new Error(`No body text found for the ${statusCode} status code`); try { var html = ejs.render(content, options); } catch (e) { res.end(e.message); return; } let postDataStr = JSON.stringify(postData || {}); let varName = options.varName || 'viteRequestData'; let varGlobal = JSON.stringify(options.global || {}); let funcName = new Date().valueOf(); let queryScript = ` function _viteGetQuery${funcName}() { var url = window.location.search; var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for(var i = 0; i < strs.length; i ++) { theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]); } } return theRequest; }` let titleStr = html.match(/<head(.*?)>/g)[0] || ""; html = html.replace( /<head(.*?)>/g, `${titleStr}<script>${queryScript};window.isGuest=${isGuest}; window.${varName} = Object.assign(_viteGetQuery${funcName}(),${postDataStr}); window._global=${varGlobal}</script> ` ) let titleEnd = html.match(/<\/head(.*?)>/g)[0] || ""; let lang = Cookies["locale"] || result["locale"] || "zh-CN"; let funcLangMap = { 'hivuiLogin/index.html': `hivuiLogin/lang/${lang}.js`, 'hivuiMain/index.html': `hivuiMain/lang/${lang}.js`, '/platf/': `hivuiBirt/lang/${lang}.js`, } let curFuncLangScript = '' for (let k in funcLangMap) { if (req.url.indexOf(k) > -1) { curFuncLangScript = `<script src="/${projectName}/${funcLangMap[k]}"></script>` break; } } html = html.replace( /<\/head(.*?)>/g, `<script src="/assets_platform/vue-i18n/vue-i18n.js"></script> <script src="/${projectName}/lang/element-ui/${lang}.js"></script> <script src="/${projectName}/lang/hi-ui/${lang}.js"></script> <script src="/${projectName}/lang/project/${lang}.js"></script> ${curFuncLangScript} <script> try{ // 统一输出语言包 zh-CN 名 if(!window.GLOBAL_LANG_TPL){ console.log('不影响运行,提示:[[${req.url},当前模板语言包不存在]]') } if(!window.GLOBAL_LANG_HIUI){ console.log('不影响运行,提示:[[${req.url},hiui语言包不存在]]') } Vue.prototype._i18n = new VueI18n({ locale: 'localelang', messages: { 'localelang':Object.assign({},window.GLOBAL_LANG_TPL||{},window.GLOBAL_LANG_HIUI||{},window.GLOBAL_LANG_PROJECT||{},window.GLOBAL_LANG_MODULE||{}), } }); (function(lang){ lang = lang.split('-'); lang= lang[0]+((lang[1]||'').charAt(0).toUpperCase() + (lang[1]||'').slice(1)); console.log(lang) ELEMENT.locale(ELEMENT.lang[lang]) })('${lang}'); }catch(e){ console.log('语言包加载出错!') } </script> <script src="/${projectName}/setting/desktop/development.js" type="text/javascript"></script> ${titleEnd}`) res.writeHead(statusCode, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, // 'Content-Length': html.length, 'Content-Type': 'html' }); res.write(html) res.end(); } var serverPath = VITE_APP_BASE_API + VITE_APP_SERVER; if (req.url.indexOf("/development.js") != -1) { let content; try { content = fs.readFileSync(req.url.substr(1), { encoding: 'utf8' }) } catch (e) { res.writeHead(404, { "Content-Type": "application/json;charset=UTF-8" }); res.end("获取", req.url + "文件异常!"); return; } try { var html = ejs.render(content, options); } catch (e) { res.end(e.message); return; } res.end(html); return; } let pathname = req._parsedUrl.pathname; //console.log(new Date(), 'req.url:', req.url) if (isFlow(pathname) || isFunc(pathname) || isInfc(pathname)) { // let url = req.url; let post = ''; postData = ''; let path; let fmodelpath = pathname; // url.split("?")[0]; var post_data = {}; // var param = req.url.split("?")[1]; if (isFlow(fmodelpath)) { var fversion = ""; var ftaskguid = ""; var fbzid = ""; if (param) { fversion = result["_version"] || result["version"]; ftaskguid = result["_ftaskguid"] || result["ftaskguid"]; fbzid = result["fbzid"]; } post_data = { fmodelpath: fmodelpath, fversion, ftaskguid, fbzid } path = serverPath + "/flow/open?origin=pre&skip=false&pn="; } else if (isInfc(fmodelpath)) { path = serverPath + fmodelpath + "?pn="; } else { var viewItemId = "" if (param) { viewItemId = result["__viewItemId"] || result["viewItemId"] || ""; } path = serverPath + fmodelpath + "?origin=pre&skip=false&viewItemId=" + viewItemId + "&pn=" } // let pn = url.split("/")[1]; const TokenKey = 'EAP-Token'; function handleFunc() { let token = Cookies[TokenKey]; let requestUrl = path + process.env.VITE_APP_PN; if (param) { requestUrl = requestUrl + "&" + param; } console.log("----requestUrl:", requestUrl, "token:", token); Object.assign(post_data, postData); let lang = Cookies["locale"] || result["locale"] || "zh-CN"; var requestOption = { url: requestUrl, method: "POST", json: true, body: post_data, headers: { "token": token, "Cookie": `locale=${lang}`, "Authorization": "Bearer " + token, "Content-Type": "application/json;charset=UTF-8" } } if (isFlow(pathname)) { requestOption["body"] = post_data; } else if (isFunc(pathname)) { //页面流用表单提交 requestOption["form"] = post_data; } request(requestOption, function (error, response, body) { //console.log(error, response, body); if (!error && response.statusCode == 200) { let pcform; let designPath; let isGuest = false; if (body) { if (isFlow(fmodelpath) && body.outParameter) { pcform = body.outParameter.task.bizpcform; if (!result["locale"] && body.outParameter.locale) { result["locale"] = body.outParameter.locale; } } else if (isFunc(fmodelpath) || isInfc(fmodelpath)) { if (body && body.logicflow || isInfc(fmodelpath)) { //逻辑流 let statusCode = body.status || response.statusCode; res.writeHead(statusCode, { "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(body)); return; } else if (body.dataPack) { pcform = body.dataPack.path; designPath = body.dataPack.designPath; isGuest = body.dataPack.isGuest; if (!result["locale"] && body.dataPack.locale) { result["locale"] = body.dataPack.locale; } } } } if (!pcform) { res.writeHead(500, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(body)); return; } if (designPath && (designPath.endsWith(".vm") || designPath.endsWith(".dvm"))) { res.writeHead(200, { 'Content-Type': 'html' }); let projectName = process.env.VITE_APP_PN.split("/")[0]; var pn = `pn=${process.env.VITE_APP_PN}` if (req.url.indexOf("?") == -1) { pn = "?" + pn; } else { pn = "&" + pn; } let accessToken = "" if (token) { accessToken = `&access_token=${token}`; } let html = ` <script src="/assets_platform/eap/eap.umd.min.js"></script> <script> window._global ={ env :"dev" } </script> <script src="/${projectName}/setting/desktop/development.js" type="text/javascript"></script> <script> window.location.href="${serverPath}${req.url}${pn}${accessToken}"; </script> ` res.end(html); return; } // var fullPath = "eaptpl/12112/mokuai/shitumulu/biaodan/dtv/1.0.0/desktop/index.html"; renderHtml(pcform, isGuest, body); } else { if (response && response.statusCode == 401) { res.writeHead(200, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, 'Content-Type': 'html' }); let projectName = process.env.VITE_APP_PN.split("/")[0]; let html = ` <script src="/assets_platform/eap/eap.umd.min.js"></script> <script> window._global ={ env :"dev" } </script> <script> if(top.window.SysPage&&top.window.SysPage.openMiniLogin){//小窗口 top.window.SysPage.openMiniLogin(true); }else{ window.location.href=window.HIVUI_SETTING.loginUrl; } </script> ` res.end(html); } else { res.writeHead(500, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(body)); } //res.end(requestUrl + ":" + JSON.stringify(error) + JSON.stringify(body)); } }, (msg) => { res.writeHead(404, { "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(msg)); // console.log(msg) }); } req.on('data', (chunk) => { post += chunk; postData = querystring.parse(post); }); req.on('end', (chunk) => { handleFunc() }); return; } else if (pathname.endsWith("studio.html")) { //动态流程 let projectName = process.env.VITE_APP_PN.split("/")[0]; let pcform = `${projectName}/hivuiStudio/index.html` renderHtml(pcform, false, {}) } else { if (isHtml(pathname)) { renderHtml(pathname.substr(1), false, {}) } else { next(); } } }) }, } } export default myPlugin;
var querystring = require('querystring'); var url = require('url'); const fs = require('fs') var https = require('https'); var request = require('request'); var ejs = require('ejs'); function myPlugin(rawOptions) { let projectName = process.env.VITE_APP_PN.split("/")[0]; var previewPath = `${projectName}/setting/studio/preview.json` var setting try { let settingContent = fs.readFileSync(previewPath, { encoding: 'utf8' }); setting = JSON.parse(settingContent) } catch (e) { console.log("preview数据有错!") } var VITE_APP_BASE_API, VITE_APP_SERVER; if (setting) { VITE_APP_BASE_API = (setting.server || {}).VITE_APP_BASE_API || process.env.VITE_APP_BASE_API; VITE_APP_SERVER = (setting.server || {}).VITE_APP_SERVER || process.env.VITE_APP_SERVER; } else { VITE_APP_BASE_API = process.env.VITE_APP_BASE_API; VITE_APP_SERVER = process.env.VITE_APP_SERVER; } const options = { isProduction: process.env.NODE_ENV === 'production', ...rawOptions, VITE_APP_BASE_API: VITE_APP_BASE_API, VITE_APP_SERVER: VITE_APP_SERVER, root: process.cwd(), }; let postData; let config; return { name: 'vite-plugin-func', // 必须的,将会显示在 warning 和 error 中 configResolved(resolvedConfig) { // 存储最终解析的配置 config = resolvedConfig }, configureServer(server) { server.middlewares.use((req, res, next) => { var Cookies = {}; if (req.headers.cookie != null) { req.headers.cookie.split(';').forEach(l => { var parts = l.split('='); Cookies[parts[0].trim()] = (parts[1] || '').trim(); }); } var param = req._parsedUrl.query; var result = {}; if (param) { let values = param.split("&"); for (let i = 0; i < values.length; i++) { const element = values[i]; let _val = element.split("="); result[_val[0]] = _val[1]; } } function isFlow(type) { return type.endsWith(".flow") || type.endsWith(".flowc"); } // 接口 function isInfc(type) { return type.endsWith(".infc") } function isFunc(type) { return type.endsWith(".func") } function isHtml(type) { return type.endsWith(".html") } // 渲染页面 function renderHtml(pcform, isGuest, body) { let content; try { content = fs.readFileSync(pcform, { encoding: 'utf8' }) } catch (e) { res.writeHead(404, { "Content-Type": "application/json;charset=UTF-8" }); res.end("pcform:" + pcform + "文件异常!"); return; } const statusCode = 200; if (!body) throw new Error(`No body text found for the ${statusCode} status code`); try { var html = ejs.render(content, options); } catch (e) { res.end(e.message); return; } let postDataStr = JSON.stringify(postData || {}); let varName = options.varName || 'viteRequestData'; let varGlobal = JSON.stringify(options.global || {}); let funcName = new Date().valueOf(); let queryScript = ` function _viteGetQuery${funcName}() { var url = window.location.search; var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for(var i = 0; i < strs.length; i ++) { theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]); } } return theRequest; }` let titleStr = html.match(/<head(.*?)>/g)[0] || ""; html = html.replace( /<head(.*?)>/g, `${titleStr}<script>${queryScript};window.isGuest=${isGuest}; window.${varName} = Object.assign(_viteGetQuery${funcName}(),${postDataStr}); window._global=${varGlobal}</script> ` ) let titleEnd = html.match(/<\/head(.*?)>/g)[0] || ""; let lang = Cookies["locale"] || result["locale"] || "zh-CN"; let funcLangMap = { 'hivuiLogin/index.html': `hivuiLogin/lang/${lang}.js`, 'hivuiMain/index.html': `hivuiMain/lang/${lang}.js`, '/platf/': `hivuiBirt/lang/${lang}.js`, } let curFuncLangScript = '' for (let k in funcLangMap) { if (req.url.indexOf(k) > -1) { curFuncLangScript = `<script src="/${projectName}/${funcLangMap[k]}"></script>` break; } } html = html.replace( /<\/head(.*?)>/g, `<script src="/assets_platform/vue-i18n/vue-i18n.js"></script> <script src="/${projectName}/lang/element-ui/${lang}.js"></script> <script src="/${projectName}/lang/hi-ui/${lang}.js"></script> <script src="/${projectName}/lang/project/${lang}.js"></script> ${curFuncLangScript} <script> try{ // 统一输出语言包 zh-CN 名 if(!window.GLOBAL_LANG_TPL){ console.log('不影响运行,提示:[[${req.url},当前模板语言包不存在]]') } if(!window.GLOBAL_LANG_HIUI){ console.log('不影响运行,提示:[[${req.url},hiui语言包不存在]]') } Vue.prototype._i18n = new VueI18n({ locale: 'localelang', messages: { 'localelang':Object.assign({},window.GLOBAL_LANG_TPL||{},window.GLOBAL_LANG_HIUI||{},window.GLOBAL_LANG_PROJECT||{},window.GLOBAL_LANG_MODULE||{}), } }); (function(lang){ lang = lang.split('-'); lang= lang[0]+((lang[1]||'').charAt(0).toUpperCase() + (lang[1]||'').slice(1)); console.log(lang) ELEMENT.locale(ELEMENT.lang[lang]) })('${lang}'); }catch(e){ console.log('语言包加载出错!') } </script> <script src="/${projectName}/setting/desktop/development.js" type="text/javascript"></script> ${titleEnd}`) res.writeHead(statusCode, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, // 'Content-Length': html.length, 'Content-Type': 'html' }); res.write(html) res.end(); } var serverPath = VITE_APP_BASE_API + VITE_APP_SERVER; if (req.url.indexOf("/development.js") != -1) { let content; try { content = fs.readFileSync(req.url.substr(1), { encoding: 'utf8' }) } catch (e) { res.writeHead(404, { "Content-Type": "application/json;charset=UTF-8" }); res.end("获取", req.url + "文件异常!"); return; } try { var html = ejs.render(content, options); } catch (e) { res.end(e.message); return; } res.end(html); return; } let pathname = req._parsedUrl.pathname; //console.log(new Date(), 'req.url:', req.url) if (isFlow(pathname) || isFunc(pathname) || isInfc(pathname)) { // let url = req.url; let post = ''; postData = ''; let path; let fmodelpath = pathname; // url.split("?")[0]; var post_data = {}; // var param = req.url.split("?")[1]; if (isFlow(fmodelpath)) { var fversion = ""; var ftaskguid = ""; var fbzid = ""; if (param) { fversion = result["_version"] || result["version"]; ftaskguid = result["_ftaskguid"] || result["ftaskguid"]; fbzid = result["fbzid"]; } post_data = { fmodelpath: fmodelpath, fversion, ftaskguid, fbzid } path = serverPath + "/flow/open?origin=pre&skip=false&pn="; } else if (isInfc(fmodelpath)) { path = serverPath + fmodelpath + "?pn="; } else { var viewItemId = "" if (param) { viewItemId = result["__viewItemId"] || result["viewItemId"] || ""; } path = serverPath + fmodelpath + "?origin=pre&skip=false&viewItemId=" + viewItemId + "&pn=" } // let pn = url.split("/")[1]; const TokenKey = 'EAP-Token'; function handleFunc() { let token = Cookies[TokenKey]; let requestUrl = path + process.env.VITE_APP_PN; if (param) { requestUrl = requestUrl + "&" + param; } console.log("----requestUrl:", requestUrl, "token:", token); Object.assign(post_data, postData); let lang = Cookies["locale"] || result["locale"] || "zh-CN"; var requestOption = { url: requestUrl, method: "POST", json: true, body: post_data, headers: { "token": token, "Cookie": `locale=${lang}`, "Authorization": "Bearer " + token, "Content-Type": "application/json;charset=UTF-8" } } if (isFlow(pathname)) { requestOption["body"] = post_data; } else if (isFunc(pathname)) { //页面流用表单提交 requestOption["form"] = post_data; } request(requestOption, function (error, response, body) { //console.log(error, response, body); if (!error && response.statusCode == 200) { let pcform; let designPath; let isGuest = false; if (body) { if (isFlow(fmodelpath) && body.outParameter) { pcform = body.outParameter.task.bizpcform; } else if (isFunc(fmodelpath) || isInfc(fmodelpath)) { if (body && body.logicflow || isInfc(fmodelpath)) { //逻辑流 let statusCode = body.status || response.statusCode; res.writeHead(statusCode, { "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(body)); return; } else if (body.dataPack) { pcform = body.dataPack.path; designPath = body.dataPack.designPath; isGuest = body.dataPack.isGuest; } } } if (!pcform) { res.writeHead(500, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(body)); return; } if (designPath && (designPath.endsWith(".vm") || designPath.endsWith(".dvm"))) { res.writeHead(200, { 'Content-Type': 'html' }); let projectName = process.env.VITE_APP_PN.split("/")[0]; var pn = `pn=${process.env.VITE_APP_PN}` if (req.url.indexOf("?") == -1) { pn = "?" + pn; } else { pn = "&" + pn; } let accessToken = "" if (token) { accessToken = `&access_token=${token}`; } let html = ` <script src="/assets_platform/eap/eap.umd.min.js"></script> <script> window._global ={ env :"dev" } </script> <script src="/${projectName}/setting/desktop/development.js" type="text/javascript"></script> <script> window.location.href="${serverPath}${req.url}${pn}${accessToken}"; </script> ` res.end(html); return; } // var fullPath = "eaptpl/12112/mokuai/shitumulu/biaodan/dtv/1.0.0/desktop/index.html"; renderHtml(pcform, isGuest, body); } else { if (response && response.statusCode == 401) { res.writeHead(200, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, 'Content-Type': 'html' }); let projectName = process.env.VITE_APP_PN.split("/")[0]; let html = ` <script src="/assets_platform/eap/eap.umd.min.js"></script> <script> window._global ={ env :"dev" } </script> <script> if(top.window.SysPage&&top.window.SysPage.openMiniLogin){//小窗口 top.window.SysPage.openMiniLogin(true); }else{ window.location.href=window.HIVUI_SETTING.loginUrl; } </script> ` res.end(html); } else { res.writeHead(500, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(body)); } //res.end(requestUrl + ":" + JSON.stringify(error) + JSON.stringify(body)); } }, (msg) => { res.writeHead(404, { "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(msg)); // console.log(msg) }); } req.on('data', (chunk) => { post += chunk; postData = querystring.parse(post); }); req.on('end', (chunk) => { handleFunc() }); return; } else if (pathname.endsWith("studio.html")) { //动态流程 let projectName = process.env.VITE_APP_PN.split("/")[0]; let pcform = `${projectName}/hivuiStudio/index.html` renderHtml(pcform, false, {}) } else { if (isHtml(pathname)) { renderHtml(pathname.substr(1), false, {}) } else { next(); } } }) }, } } export default myPlugin;
Show line notes below