fite/lib/utils.js

92 lines
2.3 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-03-08 19:09:09 +08:00
import { red, cyan, blue } from 'kolorist'
2023-05-22 15:06:33 +08:00
import { Worker } from 'node:worker_threads'
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
export function createHmrScript(legacy) {
return `
!(function vue_live_hmr(){
var ws = new WebSocket(\`ws\${location.protocol === 'https:' ? 's' : ''}://\${location.host}/ws-vue-live\`)
ws.addEventListener('open', function (r) {
if(vue_live_hmr.closed){
delete vue_live_hmr.closed
location.reload()
}
console.log('vue-live hmr ready...')
})
ws.addEventListener('close', function(){
vue_live_hmr.closed = true
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
}
})
})()
`
}
export function isCustomElement(tag) {
return tag.startsWith('wc-')
}
export function startWorker(file) {
return new Promise((resolve, reject) => {
let worker = new Worker(file)
worker.on('message', resolve)
worker.on('error', reject)
worker.on('exit', code => {
if (code !== 0) {
reject(new Error(`Worker stopped with exit code ${code}`))
}
})
})
}