fite/lib/utils.js

104 lines
2.7 KiB
JavaScript
Raw Permalink Normal View History

2023-05-22 15:06:33 +08:00
/**
* {一些工具类函数}
* @author yutent<yutent.io@gmail.com>
* @date 2023/05/22 14:52:00
*/
2023-06-13 15:32:19 +08:00
import { createHash, randomUUID } from 'node:crypto'
import { join } from 'node:path'
2023-06-13 16:21:24 +08:00
import { gzipSync } from 'node:zlib'
2023-06-13 15:32:19 +08:00
import { red, cyan, blue } from 'kolorist'
// 修正路径合并 避免在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)
}
2023-03-08 19:09:09 +08:00
2023-06-13 16:21:24 +08:00
export function gzip(val) {
return gzipSync(val)
}
2023-03-08 19:09:09 +08:00
export function friendlyErrors(pathname, ext = '') {
console.log(cyan(pathname), red(`not found!!!`))
console.log(
red('请正确填写引入的文件路径, fite 不再自动补全【%s】\n'),
blue(`/index.${ext}`)
)
}
2023-05-22 15:06:33 +08:00
2023-06-13 15:32:19 +08:00
export function createHmrScript(legacy, session = '') {
2023-05-22 15:06:33 +08:00
return `
!(function vue_live_hmr(){
2023-06-26 16:39:45 +08:00
var 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}\`)
2023-05-22 15:06:33 +08:00
ws.addEventListener('open', function (r) {
if(vue_live_hmr.closed){
delete vue_live_hmr.closed
location.reload()
}
2023-05-23 18:32:24 +08:00
console.log('fite hmr ready...')
2023-05-22 15:06:33 +08:00
})
ws.addEventListener('close', function(){
vue_live_hmr.closed = true
2023-06-26 16:39:45 +08:00
if (localStorage.getItem(location.pathname) === '1') {
return
}
2023-05-22 15:06:33 +08:00
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
}
})
})()
`
}
2023-06-16 14:19:32 +08:00
// 默认的 web components 判断
export function defaultCustomElement(tag) {
2023-05-22 15:06:33 +08:00
return tag.startsWith('wc-')
}