增加热加载支持

pull/1/head
yutent 2023-01-30 19:11:03 +08:00
parent 24e900ac04
commit 6de1901742
2 changed files with 75 additions and 24 deletions

View File

@ -4,6 +4,7 @@ import fs from 'iofs'
import { join, resolve, dirname } from 'path'
import { parse } from 'url'
import socket from './ws.js'
import chokidar from 'chokidar'
import { compileScss, parseJs, compileVue, parseHtml } from './compile-vue.js'
@ -18,19 +19,6 @@ export default async function createServer(root = '', conf = {}) {
const PORT = conf.devServer.port || 8080
const USE_HTTPS = conf.devServer.https
const DOMAIN = conf.devServer.domain || 'localhost'
const server = (USE_HTTPS ? https : http)
.createServer(SERVER_OPTIONS)
.listen(PORT)
let indexPage = Object.keys(conf.pages)
.map(it => {
let tmp = it + '.html'
return `<li><a href="/${tmp}">${tmp}</a></li>`
})
.join('')
let pagesDir = '',
currentPage = ''
if (USE_HTTPS) {
Object.assign(SERVER_OPTIONS, conf.devServer.ssl)
@ -41,6 +29,23 @@ export default async function createServer(root = '', conf = {}) {
}
}
const server = (USE_HTTPS ? https : http)
.createServer(SERVER_OPTIONS)
.listen(PORT)
const ws = socket(server)
let indexPage = Object.keys(conf.pages)
.map(it => {
let tmp = it + '.html'
return `<li><a href="/${tmp}">${tmp}</a></li>`
})
.join('')
let ready = false
let pagesDir = '',
currentPage = ''
server
.on('request', function (req, res) {
let pathname = parse(req.url.slice(1)).pathname
@ -222,9 +227,34 @@ export default async function createServer(root = '', conf = {}) {
)
})
const ws = await socket(server)
chokidar
.watch(root)
.on('all', (act, file) => {
if (ready) {
if (act === 'add' || act === 'change') {
let ext = file.slice(file.lastIndexOf('.') + 1)
console.log(ext)
console.log(ws)
switch (ext) {
case 'js':
ws.send({ action: 'reload' })
break
ws.send('hello from vue-live')
case 'css':
case 'scss':
ws.send({ action: 'render' })
break
}
}
}
})
.on('ready', () => {
ready = true
console.log('预处理完成,监听文件变化中,请勿关闭本窗口...')
})
// setInterval(() => {
// ws.send({action: Math.random() < 0.5 ? 'render' : 'reload',data:'hello from vue-live'})
// }, 2000);
}

View File

@ -1,5 +1,5 @@
/**
* {}
* 一个简单到极致的 WebSocket
* @author yutent<yutent.io@gmail.com>
* @date 2023/01/17 17:32:51
*/
@ -14,12 +14,33 @@ function defer() {
return o
}
export default function (server) {
var _ = defer()
var conn = new WebSocketServer({ server, path: '/ws-vue-live' })
class WebSocket {
#ws = null // ws实例
#queue = [] // 消息队列
conn.on('connection', client => {
_.resolve(client)
})
return _.promise
constructor(server) {
var conn = new WebSocketServer({ server, path: '/ws-vue-live' })
conn.on('connection', ws => {
this.#ws = ws
// ws.on('message', data => {
// console.log(data + '');
// })
while (this.#queue.length) {
let msg = this.#queue.shift()
this.send(msg)
}
})
}
send(msg = {}) {
if (this.#ws) {
this.#ws.send(JSON.stringify(msg))
} else {
this.#queue.push(msg)
}
}
}
export default function (server) {
return new WebSocket(server)
}