106 lines
2.8 KiB
JavaScript
106 lines
2.8 KiB
JavaScript
/**
|
|
* {一些工具类函数}
|
|
* @author yutent<yutent.io@gmail.com>
|
|
* @date 2023/05/22 14:52:00
|
|
*/
|
|
|
|
import { createHash, randomUUID } from 'node:crypto'
|
|
import { join } from 'node:path'
|
|
import { gzipSync } from 'node:zlib'
|
|
import { red, cyan, blue } from 'kolorist'
|
|
import { LEGACY_POLYFILL } from './constants.js'
|
|
|
|
// 修正路径合并 避免在windows下被转义
|
|
export function urlJoin(...args) {
|
|
return join(...args).replace(/\\/g, '/')
|
|
}
|
|
|
|
export function uuid() {
|
|
return randomUUID().slice(-8)
|
|
}
|
|
|
|
export function md5(str = '') {
|
|
let sum = createHash('md5')
|
|
sum.update(str, 'utf8')
|
|
return sum.digest('hex').slice(0, 8)
|
|
}
|
|
|
|
export function gzip(val) {
|
|
return gzipSync(val)
|
|
}
|
|
|
|
export function friendlyErrors(pathname, ext = '') {
|
|
console.log(cyan(pathname), red(`not found!!!`))
|
|
console.log(
|
|
red('请正确填写引入的文件路径, fite 不再自动补全【%s】\n'),
|
|
blue(`/index.${ext}`)
|
|
)
|
|
}
|
|
|
|
export function createHmrScript(legacy, session = '') {
|
|
return `
|
|
!(function vue_live_hmr(){
|
|
let ws = new WebSocket(\`ws\${location.protocol === 'https:' ? 's' : ''}://\${location.host}/ws-fite-hmr?session=\${btoa(location.pathname).replace(/[=\+\/]/g, '')}&lock=\${localStorage.getItem(location.pathname) || 0}\`)
|
|
|
|
ws.addEventListener('open', function (r) {
|
|
if(vue_live_hmr.closed){
|
|
delete vue_live_hmr.closed
|
|
location.reload()
|
|
}
|
|
console.log('fite hmr ready...')
|
|
})
|
|
|
|
ws.addEventListener('close', function(){
|
|
vue_live_hmr.closed = true
|
|
if (localStorage.getItem(location.pathname) === '1') {
|
|
return
|
|
}
|
|
setTimeout(vue_live_hmr, 2000)
|
|
})
|
|
|
|
ws.addEventListener('message', function (ev) {
|
|
var { action, data } = JSON.parse(ev.data)
|
|
|
|
switch (action) {
|
|
case 'reload':
|
|
location.reload()
|
|
break
|
|
|
|
case 'render':
|
|
{
|
|
${
|
|
legacy
|
|
? `
|
|
let stylesheet = document.head.children.namedItem(data.path)
|
|
if (stylesheet) {
|
|
stylesheet.textContent = data.content
|
|
}
|
|
`
|
|
: `
|
|
let tmp = [...document.adoptedStyleSheets]
|
|
for (let i = -1, it; (it = tmp[++i]); ) {
|
|
if (it.path === data.path) {
|
|
let stylesheet = new CSSStyleSheet()
|
|
stylesheet.path = data.path
|
|
stylesheet.replaceSync(data.content)
|
|
tmp[i] = stylesheet
|
|
document.adoptedStyleSheets = tmp
|
|
break
|
|
}
|
|
}
|
|
`
|
|
}
|
|
}
|
|
break
|
|
}
|
|
})
|
|
${LEGACY_POLYFILL}
|
|
})()
|
|
`
|
|
}
|
|
|
|
// 默认的 web components 判断
|
|
export function defaultCustomElement(tag) {
|
|
return tag.startsWith('wc-')
|
|
}
|