446 lines
14 KiB
JavaScript
446 lines
14 KiB
JavaScript
import http from 'node:http'
|
|
import https from 'node:http2'
|
|
import fs from 'iofs'
|
|
import { join, dirname } from 'node:path'
|
|
import { parse } from 'node:url'
|
|
import socket from './ws.js'
|
|
import chokidar from 'chokidar'
|
|
import { red } from 'kolorist'
|
|
|
|
import { friendlyErrors, defaultCustomElement, gzip } from './utils.js'
|
|
|
|
import { compileScss, parseJs, compileVue, parseHtml } from './compile-vue.js'
|
|
|
|
import MIME_TYPES from './mime-tpyes.js'
|
|
import { COMMON_HEADERS } from './constants.js'
|
|
|
|
const noc = Buffer.from('')
|
|
const SERVER_OPTIONS = { allowHTTP1: true }
|
|
const CACHE = {} //文件缓存, 用于hmr
|
|
|
|
function readFile(file) {
|
|
return (file && fs.cat(file)?.toString()) || ''
|
|
}
|
|
|
|
export default async function createServer(root = '', conf = {}) {
|
|
const SOURCE_DIR = join(root, 'src')
|
|
const PUBLIC_DIR = join(root, 'public')
|
|
const DEPLOY_PATH = conf.base || '' // 部署目录, 默认是根目录部署
|
|
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 INJECT_SCSS = readFile(conf.inject?.scss)
|
|
const LEGACY_MODE = !!conf.legacy
|
|
const ENABLE_GZIP = !!conf.devServer.gzip
|
|
const { isCustomElement = defaultCustomElement } = conf.compileOptions || {}
|
|
|
|
if (conf.imports['vue-dev']) {
|
|
conf.imports.vue = conf.imports['vue-dev']
|
|
}
|
|
if (conf.imports['vue-router-dev']) {
|
|
conf.imports['vue-router'] = conf.imports['vue-router-dev']
|
|
}
|
|
|
|
if (conf.devServer.headers) {
|
|
Object.assign(COMMON_HEADERS, conf.devServer.headers)
|
|
}
|
|
|
|
if (USE_HTTPS) {
|
|
Object.assign(SERVER_OPTIONS, conf.devServer.ssl)
|
|
|
|
if (!SERVER_OPTIONS.key || !SERVER_OPTIONS.cert) {
|
|
console.error('证书错误: https 证书不能为空!!!\n')
|
|
process.exit()
|
|
}
|
|
}
|
|
|
|
const server = (USE_HTTPS ? https : http)
|
|
[USE_HTTPS ? 'createSecureServer' : '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="${DEPLOY_PATH + tmp}">${DEPLOY_PATH + tmp}</a></li>`
|
|
})
|
|
.join('')
|
|
|
|
let ready = false
|
|
let pagesDir = '',
|
|
currentPage = ''
|
|
|
|
server
|
|
.on('request', function (req, res) {
|
|
let prefix = DEPLOY_PATH ? DEPLOY_PATH.replace(/\/$/, '') : ''
|
|
let url =
|
|
prefix && req.url.startsWith(prefix)
|
|
? req.url.slice(DEPLOY_PATH.length)
|
|
: req.url.slice(1)
|
|
let pathname = parse(url).pathname
|
|
let pageName = '',
|
|
isIndex = false // 是否渲染目录页
|
|
let ext
|
|
|
|
if (prefix && req.url === '/') {
|
|
res.setHeader('Location', DEPLOY_PATH)
|
|
res.writeHead(302, USE_HTTPS ? void 0 : 'Redirect')
|
|
return res.end('')
|
|
}
|
|
|
|
if (pathname) {
|
|
// 这种情况是, 页面是子目录的情况
|
|
if (pathname.includes('/') && pathname.endsWith('.html')) {
|
|
pageName = pathname.slice(0, -5)
|
|
if (conf.pages[pageName]) {
|
|
ext = 'html'
|
|
currentPage = pageName
|
|
pagesDir = dirname(conf.pages[pageName]?.entry)
|
|
}
|
|
} else {
|
|
pathname = pathname.split('/')
|
|
|
|
if (pathname[0].endsWith('.html')) {
|
|
pageName = pathname.shift()
|
|
|
|
let tmp = pageName.split('.')
|
|
|
|
ext = tmp.pop()
|
|
pageName = tmp.join('.')
|
|
// 页面不存在时输出404, 避免进程崩溃退出
|
|
if (!conf.pages[pageName]) {
|
|
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
|
|
return res.end(`Oops!!! 404 Not Found`)
|
|
}
|
|
|
|
currentPage = pageName
|
|
pagesDir = dirname(conf.pages[pageName]?.entry)
|
|
} else {
|
|
if (currentPage) {
|
|
let tmp = pathname.at(-1).split('.')
|
|
// 修正history路由时的访问
|
|
ext = tmp.length > 1 ? tmp.pop() : 'html'
|
|
pageName = currentPage
|
|
} else {
|
|
pageName = Object.keys(conf.pages).pop()
|
|
currentPage = pageName
|
|
pagesDir = dirname(conf.pages[pageName].entry)
|
|
ext = 'html'
|
|
}
|
|
}
|
|
pathname = pathname.join('/')
|
|
}
|
|
} else {
|
|
if (IS_MPA) {
|
|
isIndex = true
|
|
} else {
|
|
pageName = Object.keys(conf.pages).pop()
|
|
currentPage = pageName
|
|
pagesDir = dirname(conf.pages[pageName].entry)
|
|
ext = 'html'
|
|
}
|
|
}
|
|
|
|
for (let k in COMMON_HEADERS) {
|
|
res.setHeader(k, COMMON_HEADERS[k])
|
|
}
|
|
|
|
if (isIndex) {
|
|
res.setHeader('content-type', MIME_TYPES.html)
|
|
res.writeHead(200, USE_HTTPS ? void 0 : 'OK')
|
|
res.end(
|
|
'<style>body{font:14px/1.5 Arial}ol{display:flex;flex-wrap:wrap;}li{width:30%;}a{color:teal}a:visited{color:orange;}</style>' +
|
|
'<div>注意: 你看到这个页面, 仅在开发时可见。<br>仅为了方便开发多页应用时访问自己想要修改的页面, 而不需要手动输入地址。</div><ol>' +
|
|
indexPage +
|
|
'</ol>'
|
|
)
|
|
} else {
|
|
res.setHeader('accept-ranges', 'bytes')
|
|
|
|
let code = ''
|
|
|
|
switch (ext) {
|
|
case 'html':
|
|
{
|
|
res.setHeader('content-type', MIME_TYPES.html)
|
|
|
|
let page = conf.pages[pageName]
|
|
let entry = fs.cat(page.entry)?.toString()
|
|
let html = fs.cat(join(process.cwd(), 'index.html')).toString()
|
|
|
|
entry = parseJs(
|
|
entry,
|
|
conf.imports,
|
|
{
|
|
IS_MPA,
|
|
currentPage,
|
|
IS_ENTRY: true,
|
|
DEPLOY_PATH,
|
|
LEGACY_MODE
|
|
},
|
|
page.entry
|
|
)
|
|
|
|
code = parseHtml(html, {
|
|
page,
|
|
imports: conf.imports,
|
|
entry,
|
|
LEGACY_MODE
|
|
})
|
|
}
|
|
|
|
break
|
|
|
|
case 'vue':
|
|
{
|
|
let rpath = pathname.replace('@/', '')
|
|
let file
|
|
|
|
if (IS_MPA) {
|
|
// 判断前后2个值相等, 避免出现目录名和页面名字相同时走错逻辑
|
|
if (rpath === pathname && rpath.startsWith(currentPage)) {
|
|
file = join(pagesDir, rpath.slice(currentPage.length))
|
|
} else {
|
|
file = join(SOURCE_DIR, rpath)
|
|
}
|
|
} else {
|
|
file = join(SOURCE_DIR, rpath)
|
|
}
|
|
if (!fs.isfile(file)) {
|
|
friendlyErrors(pathname, ext)
|
|
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
|
|
res.end('')
|
|
return
|
|
}
|
|
|
|
code = compileVue(file, conf.imports, {
|
|
IS_MPA,
|
|
currentPage,
|
|
SOURCE_DIR,
|
|
CACHE,
|
|
DEPLOY_PATH,
|
|
INJECT_SCSS,
|
|
LEGACY_MODE,
|
|
isCustomElement
|
|
})
|
|
|
|
res.setHeader('content-type', MIME_TYPES.js)
|
|
}
|
|
break
|
|
|
|
case 'scss':
|
|
case 'css':
|
|
{
|
|
let file = join(SOURCE_DIR, pathname.replace('@/', ''))
|
|
if (!fs.isfile(file)) {
|
|
file = join(PUBLIC_DIR, pathname.replace('@/', ''))
|
|
|
|
if (!fs.isfile(file)) {
|
|
friendlyErrors(pathname, ext)
|
|
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
|
|
res.end('')
|
|
return
|
|
}
|
|
}
|
|
if (file === conf.inject?.scss) {
|
|
console.log(red('设置为注入的样式文件不可被vue/js文件引用\n'))
|
|
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
|
|
res.end('')
|
|
return
|
|
}
|
|
code = compileScss(file)
|
|
res.setHeader('content-type', MIME_TYPES.css)
|
|
}
|
|
break
|
|
|
|
case 'json':
|
|
case 'js':
|
|
{
|
|
let rpath = pathname.replace('@/', '')
|
|
let file
|
|
|
|
if (IS_MPA) {
|
|
// 判断前后2个值相等, 避免出现目录名和页面名字相同时走错逻辑
|
|
if (rpath === pathname && rpath.startsWith(currentPage)) {
|
|
file = join(pagesDir, rpath.slice(currentPage.length))
|
|
} else {
|
|
file = join(SOURCE_DIR, rpath)
|
|
}
|
|
} else {
|
|
file = join(SOURCE_DIR, rpath)
|
|
}
|
|
|
|
if (fs.isfile(file)) {
|
|
code = fs.cat(file)
|
|
} else if (fs.isfile(join(PUBLIC_DIR, rpath))) {
|
|
file = join(PUBLIC_DIR, rpath)
|
|
code = fs.cat(file)
|
|
} else {
|
|
friendlyErrors(rpath, ext)
|
|
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
|
|
res.end('')
|
|
return
|
|
}
|
|
if (ext === 'js') {
|
|
code = parseJs(
|
|
code + '',
|
|
conf.imports,
|
|
{
|
|
IS_MPA,
|
|
currentPage,
|
|
DEPLOY_PATH,
|
|
LEGACY_MODE
|
|
},
|
|
file
|
|
)
|
|
}
|
|
res.setHeader('content-type', MIME_TYPES[ext])
|
|
}
|
|
|
|
break
|
|
|
|
default:
|
|
res.setHeader('content-type', MIME_TYPES[ext] || MIME_TYPES.other)
|
|
let pub_file = join(PUBLIC_DIR, pathname)
|
|
let source_file = join(SOURCE_DIR, pathname)
|
|
|
|
if (fs.isfile(pub_file)) {
|
|
code = fs.cat(pub_file)
|
|
if (code) {
|
|
let stat = fs.stat(pub_file)
|
|
res.setHeader(
|
|
'Last-Modified',
|
|
new Date(stat.mtime).toGMTString()
|
|
)
|
|
}
|
|
} else if (fs.isfile(source_file)) {
|
|
code = fs.cat(source_file)
|
|
if (code) {
|
|
let stat = fs.stat(source_file)
|
|
res.setHeader(
|
|
'Last-Modified',
|
|
new Date(stat.mtime).toGMTString()
|
|
)
|
|
}
|
|
} else {
|
|
code = null
|
|
}
|
|
if (code === null) {
|
|
friendlyErrors(pathname, ext)
|
|
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
|
|
res.end('')
|
|
return
|
|
}
|
|
break
|
|
}
|
|
|
|
if (ENABLE_GZIP) {
|
|
code = gzip(code || noc)
|
|
res.setHeader('Content-Encoding', 'gzip')
|
|
} else {
|
|
code = code || noc
|
|
}
|
|
|
|
res.setHeader('Content-Length', Buffer.byteLength(code))
|
|
res.writeHead(200, USE_HTTPS ? void 0 : 'OK')
|
|
res.end(code)
|
|
}
|
|
})
|
|
|
|
.on('error', err => {
|
|
console.log(
|
|
red(`${PORT} 端口被占用!!! 尝试使用 ${PORT + 1} 端口...`),
|
|
'\n'
|
|
)
|
|
conf.devServer.port = PORT + 1
|
|
createServer(root, conf)
|
|
})
|
|
.on('listening', _ => {
|
|
console.log('启动成功, 可通过以下地址访问')
|
|
console.log(
|
|
' 本地: %s://%s:%d%s',
|
|
USE_HTTPS ? 'https' : 'http',
|
|
USE_HTTPS ? 'localhost' : '127.0.0.1',
|
|
PORT,
|
|
DEPLOY_PATH
|
|
)
|
|
console.log(
|
|
' 外网: %s://%s:%d%s\n',
|
|
USE_HTTPS ? 'https' : 'http',
|
|
DOMAIN,
|
|
PORT,
|
|
DEPLOY_PATH
|
|
)
|
|
chokidar
|
|
.watch([SOURCE_DIR, PUBLIC_DIR, join(root, './index.html')])
|
|
.on('all', (act, filePath) => {
|
|
if (ready) {
|
|
let file = filePath.slice(SOURCE_DIR.length)
|
|
|
|
if (act === 'add' || act === 'change') {
|
|
let ext = file.slice(file.lastIndexOf('.') + 1)
|
|
|
|
switch (ext) {
|
|
case 'css':
|
|
case 'scss':
|
|
{
|
|
let content = ''
|
|
if (filePath === conf.inject?.scss) {
|
|
return
|
|
}
|
|
if (ext === 'scss') {
|
|
content = compileScss(filePath)
|
|
} else {
|
|
content = fs.cat(filePath).toString()
|
|
}
|
|
ws.send({
|
|
action: 'render',
|
|
data: { path: file.replace(/\\/g, '/'), content }
|
|
})
|
|
}
|
|
break
|
|
|
|
case 'vue':
|
|
{
|
|
let content = compileVue(filePath, conf.imports, {
|
|
IS_MPA,
|
|
currentPage,
|
|
SOURCE_DIR,
|
|
CACHE,
|
|
DEPLOY_PATH,
|
|
INJECT_SCSS,
|
|
LEGACY_MODE,
|
|
isCustomElement
|
|
})
|
|
let tmp = CACHE[filePath]
|
|
if (tmp.changed) {
|
|
ws.send({ action: 'reload' })
|
|
} else {
|
|
ws.send({
|
|
action: 'render',
|
|
data: {
|
|
path: file.replace(/\\/g, '/'),
|
|
content: tmp.css
|
|
}
|
|
})
|
|
}
|
|
}
|
|
break
|
|
|
|
default:
|
|
ws.send({ action: 'reload' })
|
|
break
|
|
}
|
|
} else if (act === 'unlink' || act === 'unlinkDir') {
|
|
ws.send({ action: 'reload' })
|
|
}
|
|
}
|
|
})
|
|
.on('ready', () => {
|
|
ready = true
|
|
})
|
|
})
|
|
}
|