增加热加载

pull/1/head
yutent 2023-01-17 18:43:05 +08:00
parent ab563d0980
commit 24e900ac04
3 changed files with 181 additions and 144 deletions

View File

@ -3,6 +3,7 @@ import https from 'https'
import fs from 'iofs'
import { join, resolve, dirname } from 'path'
import { parse } from 'url'
import socket from './ws.js'
import { compileScss, parseJs, compileVue, parseHtml } from './compile-vue.js'
@ -12,12 +13,15 @@ import { COMMON_HEADERS } from './constants.js'
const noc = Buffer.from('')
const SERVER_OPTIONS = {}
export default function createServer(root = '', conf = {}) {
export default async function createServer(root = '', conf = {}) {
const IS_MPA = Object.keys(conf.pages).length > 1
const PORT = conf.devServer.port || 8080
const USE_HTTPS = conf.devServer.https
const DOMAIN = conf.devServer.domain || 'localhost'
const WEB_SERVER = USE_HTTPS ? https : http
const server = (USE_HTTPS ? https : http)
.createServer(SERVER_OPTIONS)
.listen(PORT)
let indexPage = Object.keys(conf.pages)
.map(it => {
let tmp = it + '.html'
@ -37,7 +41,8 @@ export default function createServer(root = '', conf = {}) {
}
}
WEB_SERVER.createServer(SERVER_OPTIONS, function (req, res) {
server
.on('request', function (req, res) {
let pathname = parse(req.url.slice(1)).pathname
let pageName = '',
isIndex = false // 是否渲染目录页
@ -195,7 +200,7 @@ export default function createServer(root = '', conf = {}) {
res.end(code || noc)
}
})
.listen(PORT)
.on('error', err => {
console.log(`${PORT}端口被占用~~~`)
conf.devServer.port = PORT + 1
@ -216,4 +221,10 @@ export default function createServer(root = '', conf = {}) {
PORT
)
})
const ws = await socket(server)
console.log(ws)
ws.send('hello from vue-live')
}

25
lib/ws.js Normal file
View File

@ -0,0 +1,25 @@
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2023/01/17 17:32:51
*/
import { WebSocketServer } from 'ws'
function defer() {
var o = {}
o.promise = new Promise((resolve, reject) => {
o.resolve = resolve
o.reject = reject
})
return o
}
export default function (server) {
var _ = defer()
var conn = new WebSocketServer({ server, path: '/ws-vue-live' })
conn.on('connection', client => {
_.resolve(client)
})
return _.promise
}

View File

@ -9,6 +9,7 @@
"@bytedo/sass": "^1.54.8",
"chokidar": "^3.5.3",
"esbuild": "^0.15.13",
"iofs": "^1.5.2"
"iofs": "^1.5.2",
"ws": "^8.12.0"
}
}