fite/lib/dev.js

490 lines
15 KiB
JavaScript
Raw Normal View History

2023-05-22 15:06:33 +08:00
import http from 'node:http'
2023-06-13 15:32:19 +08:00
import https from 'node:http2'
2022-10-09 19:19:21 +08:00
import fs from 'iofs'
2023-05-22 15:06:33 +08:00
import { join, dirname } from 'node:path'
import { parse } from 'node:url'
2023-01-17 18:43:05 +08:00
import socket from './ws.js'
2023-01-30 19:11:03 +08:00
import chokidar from 'chokidar'
import { red } from 'kolorist'
2022-10-09 19:19:21 +08:00
2023-06-26 16:39:45 +08:00
import { friendlyErrors, defaultCustomElement, gzip } from './utils.js'
2023-03-08 19:09:09 +08:00
2022-10-11 19:31:04 +08:00
import { compileScss, parseJs, compileVue, parseHtml } from './compile-vue.js'
2022-10-09 19:19:21 +08:00
import MIME_TYPES from './mime-tpyes.js'
import { COMMON_HEADERS } from './constants.js'
2022-10-10 19:32:10 +08:00
const noc = Buffer.from('')
2023-06-13 15:32:19 +08:00
const SERVER_OPTIONS = { allowHTTP1: true }
2023-01-31 19:17:38 +08:00
const CACHE = {} //文件缓存, 用于hmr
2022-10-09 19:19:21 +08:00
2023-05-16 14:17:40 +08:00
function readFile(file) {
return (file && fs.cat(file)?.toString()) || ''
}
2023-01-17 18:43:05 +08:00
export default async function createServer(root = '', conf = {}) {
2023-02-16 15:32:17 +08:00
const SOURCE_DIR = join(root, 'src')
const PUBLIC_DIR = join(root, 'public')
2023-02-19 16:52:55 +08:00
const DEPLOY_PATH = conf.base || '' // 部署目录, 默认是根目录部署
2022-10-10 15:05:30 +08:00
const IS_MPA = Object.keys(conf.pages).length > 1
2022-10-19 17:46:32 +08:00
const PORT = conf.devServer.port || 8080
2022-10-19 17:41:50 +08:00
const USE_HTTPS = conf.devServer.https
const DOMAIN = conf.devServer.domain || 'localhost'
2023-05-16 14:17:40 +08:00
const INJECT_SCSS = readFile(conf.inject?.scss)
const LEGACY_MODE = !!conf.legacy
2023-06-13 16:21:24 +08:00
const ENABLE_GZIP = !!conf.devServer.gzip
2023-06-16 14:19:32 +08:00
const { isCustomElement = defaultCustomElement } = conf.compileOptions || {}
2024-07-25 16:30:30 +08:00
const { plugin = [], define = {} } = conf
2023-01-30 19:11:03 +08:00
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)
}
2023-01-30 19:11:03 +08:00
if (USE_HTTPS) {
Object.assign(SERVER_OPTIONS, conf.devServer.ssl)
if (!SERVER_OPTIONS.key || !SERVER_OPTIONS.cert) {
console.error('证书错误: https 证书不能为空!!!\n')
2023-02-21 18:34:48 +08:00
process.exit()
2023-01-30 19:11:03 +08:00
}
}
2023-01-17 18:43:05 +08:00
const server = (USE_HTTPS ? https : http)
2023-06-13 15:32:19 +08:00
[USE_HTTPS ? 'createSecureServer' : 'createServer'](SERVER_OPTIONS)
2023-01-17 18:43:05 +08:00
.listen(PORT)
2023-01-30 19:11:03 +08:00
const ws = socket(server)
2022-10-10 15:05:30 +08:00
let indexPage = Object.keys(conf.pages)
.map(it => {
let tmp = it + '.html'
2023-02-19 16:52:55 +08:00
return `<li><a href="${DEPLOY_PATH + tmp}">${DEPLOY_PATH + tmp}</a></li>`
2022-10-10 15:05:30 +08:00
})
.join('')
2022-10-09 19:19:21 +08:00
2023-01-30 19:11:03 +08:00
let ready = false
2022-10-10 15:05:30 +08:00
let pagesDir = '',
currentPage = ''
2022-10-09 19:19:21 +08:00
2023-01-17 18:43:05 +08:00
server
2024-07-25 16:30:30 +08:00
.on('request', async function (req, res) {
let prefix = DEPLOY_PATH ? DEPLOY_PATH.replace(/\/$/, '') : ''
2023-02-19 16:52:55 +08:00
let url =
prefix && req.url.startsWith(prefix)
2023-02-19 16:52:55 +08:00
? req.url.slice(DEPLOY_PATH.length)
: req.url.slice(1)
let pathname = parse(url).pathname
2023-01-17 18:43:05 +08:00
let pageName = '',
isIndex = false // 是否渲染目录页
let ext
2022-10-10 15:05:30 +08:00
if (prefix && req.url === '/') {
res.setHeader('Location', DEPLOY_PATH)
2023-06-13 15:32:19 +08:00
res.writeHead(302, USE_HTTPS ? void 0 : 'Redirect')
return res.end('')
}
2023-01-17 18:43:05 +08:00
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('/')
2022-10-10 15:05:30 +08:00
if (pathname[0].endsWith('.html')) {
pageName = pathname.shift()
2022-10-10 15:05:30 +08:00
let tmp = pageName.split('.')
2022-10-19 17:41:50 +08:00
ext = tmp.pop()
pageName = tmp.join('.')
// 页面不存在时输出404, 避免进程崩溃退出
if (!conf.pages[pageName]) {
2023-06-13 15:32:19 +08:00
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
return res.end(`Oops!!! 404 Not Found`)
}
2022-10-19 17:41:50 +08:00
2023-01-17 18:43:05 +08:00
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'
}
2023-01-17 18:43:05 +08:00
}
pathname = pathname.join('/')
2023-01-17 18:43:05 +08:00
}
2022-10-10 15:05:30 +08:00
} else {
2023-01-17 18:43:05 +08:00
if (IS_MPA) {
isIndex = true
2022-12-29 17:07:33 +08:00
} else {
pageName = Object.keys(conf.pages).pop()
currentPage = pageName
pagesDir = dirname(conf.pages[pageName].entry)
ext = 'html'
}
2022-10-10 15:05:30 +08:00
}
2022-10-09 19:19:21 +08:00
2023-01-17 18:43:05 +08:00
for (let k in COMMON_HEADERS) {
res.setHeader(k, COMMON_HEADERS[k])
}
2022-10-09 19:19:21 +08:00
2023-01-17 18:43:05 +08:00
if (isIndex) {
res.setHeader('content-type', MIME_TYPES.html)
2023-06-13 15:32:19 +08:00
res.writeHead(200, USE_HTTPS ? void 0 : 'OK')
2023-05-16 15:09:13 +08:00
res.end(
2023-06-13 17:45:12 +08:00
'<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>' +
2023-05-16 15:09:13 +08:00
indexPage +
2023-06-13 17:45:12 +08:00
'</ol>'
2023-05-16 15:09:13 +08:00
)
2023-01-17 18:43:05 +08:00
} else {
res.setHeader('accept-ranges', 'bytes')
2022-10-09 19:19:21 +08:00
2023-01-17 18:43:05 +08:00
let code = ''
2022-10-09 19:19:21 +08:00
2023-01-17 18:43:05 +08:00
switch (ext) {
case 'html':
{
res.setHeader('content-type', MIME_TYPES.html)
2022-10-09 19:19:21 +08:00
2023-01-17 18:43:05 +08:00
let page = conf.pages[pageName]
let entry = fs.cat(page.entry)?.toString()
2023-01-17 18:43:05 +08:00
let html = fs.cat(join(process.cwd(), 'index.html')).toString()
2022-10-11 19:31:04 +08:00
entry = parseJs(
entry,
conf.imports,
{
IS_MPA,
currentPage,
IS_ENTRY: true,
DEPLOY_PATH,
2024-08-01 13:55:40 +08:00
LEGACY_MODE,
isCustomElement,
plugin,
define
},
page.entry
)
2022-10-11 19:31:04 +08:00
2024-07-25 16:30:30 +08:00
for (let fn of plugin) {
entry = await fn('js', entry)
}
code = parseHtml(html, {
page,
imports: conf.imports,
entry,
2023-06-26 16:39:45 +08:00
LEGACY_MODE
})
2023-01-17 18:43:05 +08:00
}
2022-10-09 19:19:21 +08:00
2023-01-17 18:43:05 +08:00
break
case 'vue':
{
let rpath = pathname.replace('@/', '')
2023-01-17 18:43:05 +08:00
let file
if (IS_MPA) {
// 判断前后2个值相等, 避免出现目录名和页面名字相同时走错逻辑
if (rpath === pathname && rpath.startsWith(currentPage)) {
2023-03-17 17:56:05 +08:00
file = join(pagesDir, rpath.slice(currentPage.length))
} else {
file = join(SOURCE_DIR, rpath)
}
2023-01-17 18:43:05 +08:00
} else {
2023-02-16 15:32:17 +08:00
file = join(SOURCE_DIR, rpath)
2023-01-17 18:43:05 +08:00
}
if (!fs.isfile(file)) {
2023-03-08 19:09:09 +08:00
friendlyErrors(pathname, ext)
2023-06-13 15:32:19 +08:00
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
2023-02-21 21:27:08 +08:00
res.end('')
return
2023-01-17 18:43:05 +08:00
}
2024-07-25 16:30:30 +08:00
code = await compileVue(file, conf.imports, {
2023-01-17 18:43:05 +08:00
IS_MPA,
currentPage,
2023-02-16 15:32:17 +08:00
SOURCE_DIR,
2023-02-19 16:52:55 +08:00
CACHE,
2023-05-16 14:17:40 +08:00
DEPLOY_PATH,
INJECT_SCSS,
2023-05-22 15:06:33 +08:00
LEGACY_MODE,
2024-07-25 16:30:30 +08:00
isCustomElement,
plugin,
define
2023-01-17 18:43:05 +08:00
})
2023-01-31 19:17:38 +08:00
2024-07-25 16:30:30 +08:00
for (let fn of plugin) {
code = await fn('js', code)
}
2023-01-17 18:43:05 +08:00
res.setHeader('content-type', MIME_TYPES.js)
2022-10-09 19:19:21 +08:00
}
2023-01-17 18:43:05 +08:00
break
case 'scss':
case 'css':
{
let file = join(SOURCE_DIR, pathname.replace('@/', ''))
2023-03-08 19:09:09 +08:00
if (!fs.isfile(file)) {
file = join(PUBLIC_DIR, pathname.replace('@/', ''))
2023-03-08 19:09:09 +08:00
if (!fs.isfile(file)) {
friendlyErrors(pathname, ext)
2023-06-13 15:32:19 +08:00
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
2023-03-08 19:09:09 +08:00
res.end('')
return
}
}
2023-05-16 14:29:34 +08:00
if (file === conf.inject?.scss) {
console.log(red('设置为注入的样式文件不可被vue/js文件引用\n'))
2023-06-13 15:32:19 +08:00
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
2023-05-16 14:29:34 +08:00
res.end('')
return
}
2023-01-17 18:43:05 +08:00
code = compileScss(file)
2024-07-25 16:30:30 +08:00
for (let fn of plugin) {
code = await fn('css', code)
}
2023-01-17 18:43:05 +08:00
res.setHeader('content-type', MIME_TYPES.css)
2022-10-09 19:19:21 +08:00
}
2023-01-17 18:43:05 +08:00
break
case 'js':
2024-08-01 13:55:40 +08:00
case 'wasm':
2023-01-17 18:43:05 +08:00
{
let rpath = pathname.replace('@/', '')
2023-01-17 18:43:05 +08:00
let file
let isJson = false
2024-08-01 13:55:40 +08:00
let isWasm = rpath.endsWith('.wasm')
if (rpath.endsWith('json.js')) {
isJson = true
rpath = rpath.slice(0, -3)
}
2023-03-17 17:56:05 +08:00
if (IS_MPA) {
// 判断前后2个值相等, 避免出现目录名和页面名字相同时走错逻辑
if (rpath === pathname && rpath.startsWith(currentPage)) {
2023-03-17 17:56:05 +08:00
file = join(pagesDir, rpath.slice(currentPage.length))
} else {
2023-03-17 17:56:05 +08:00
file = join(SOURCE_DIR, rpath)
2023-03-16 19:55:00 +08:00
}
2023-01-17 18:43:05 +08:00
} else {
2023-03-17 17:56:05 +08:00
file = join(SOURCE_DIR, rpath)
2023-01-17 18:43:05 +08:00
}
2023-01-17 18:43:05 +08:00
if (fs.isfile(file)) {
code = fs.cat(file)
2023-03-17 17:56:05 +08:00
} else if (fs.isfile(join(PUBLIC_DIR, rpath))) {
file = join(PUBLIC_DIR, rpath)
code = fs.cat(file)
2023-01-17 18:43:05 +08:00
} else {
2023-03-17 17:56:05 +08:00
friendlyErrors(rpath, ext)
2023-06-13 15:32:19 +08:00
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
2023-02-21 21:27:08 +08:00
res.end('')
return
2023-01-17 18:43:05 +08:00
}
if (isJson) {
try {
code =
'export default ' + JSON.stringify(JSON.parse(code + ''))
} catch (err) {
console.log('%s 语法错误: %s', rpath, red(err.message))
}
2024-08-01 13:55:40 +08:00
} else if (isWasm) {
//
} else {
code = parseJs(
code + '',
conf.imports,
{
IS_MPA,
currentPage,
DEPLOY_PATH,
2024-08-01 13:55:40 +08:00
LEGACY_MODE,
isCustomElement,
plugin,
define
},
file
)
2024-07-25 16:30:30 +08:00
for (let fn of plugin) {
code = await fn('js', code)
}
}
res.setHeader('content-type', MIME_TYPES[ext])
2022-10-10 19:32:10 +08:00
}
2023-01-17 18:43:05 +08:00
break
2023-02-19 16:52:55 +08:00
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()
)
}
2023-02-19 16:52:55 +08:00
} else {
code = null
2023-02-16 15:32:17 +08:00
}
2023-01-17 18:43:05 +08:00
if (code === null) {
2023-03-08 19:09:09 +08:00
friendlyErrors(pathname, ext)
2023-06-13 15:32:19 +08:00
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
2023-01-17 18:43:05 +08:00
res.end('')
return
2022-10-19 17:41:50 +08:00
}
2023-01-17 18:43:05 +08:00
break
}
2022-10-19 17:41:50 +08:00
2023-06-13 16:21:24 +08:00
if (ENABLE_GZIP) {
code = gzip(code || noc)
res.setHeader('Content-Encoding', 'gzip')
} else {
code = code || noc
}
res.setHeader('Content-Length', Buffer.byteLength(code))
2023-06-13 15:32:19 +08:00
res.writeHead(200, USE_HTTPS ? void 0 : 'OK')
2023-06-13 16:21:24 +08:00
res.end(code)
2022-10-09 19:19:21 +08:00
}
2023-01-17 18:43:05 +08:00
})
2022-10-19 17:41:50 +08:00
2022-10-09 19:19:21 +08:00
.on('error', err => {
2023-02-01 10:51:33 +08:00
console.log(
red(`${PORT} 端口被占用!!! 尝试使用 ${PORT + 1} 端口...`),
'\n'
)
2022-10-19 17:46:32 +08:00
conf.devServer.port = PORT + 1
createServer(root, conf)
2022-10-09 19:19:21 +08:00
})
.on('listening', _ => {
2022-10-19 17:41:50 +08:00
console.log('启动成功, 可通过以下地址访问')
2023-01-13 11:40:53 +08:00
console.log(
2023-02-19 16:52:55 +08:00
' 本地: %s://%s:%d%s',
2023-01-13 11:40:53 +08:00
USE_HTTPS ? 'https' : 'http',
2023-05-16 15:09:13 +08:00
USE_HTTPS ? 'localhost' : '127.0.0.1',
2023-02-19 16:52:55 +08:00
PORT,
DEPLOY_PATH
2023-01-13 11:40:53 +08:00
)
console.log(
2023-02-19 16:52:55 +08:00
' 外网: %s://%s:%d%s\n',
2023-01-13 11:40:53 +08:00
USE_HTTPS ? 'https' : 'http',
DOMAIN,
2023-02-19 16:52:55 +08:00
PORT,
DEPLOY_PATH
2023-01-13 11:40:53 +08:00
)
chokidar
.watch([SOURCE_DIR, PUBLIC_DIR, join(root, './index.html')])
2024-07-25 16:30:30 +08:00
.on('all', async (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':
{
2023-05-16 14:17:40 +08:00
let content = ''
if (filePath === conf.inject?.scss) {
return
}
if (ext === 'scss') {
content = compileScss(filePath)
} else {
content = fs.cat(filePath).toString()
}
2024-07-25 16:30:30 +08:00
for (let fn of plugin) {
content = await fn('css', content)
}
ws.send({
action: 'render',
data: { path: file.replace(/\\/g, '/'), content }
})
}
break
case 'vue':
{
2024-07-25 16:30:30 +08:00
let content = await compileVue(filePath, conf.imports, {
IS_MPA,
currentPage,
SOURCE_DIR,
CACHE,
2023-05-16 14:17:40 +08:00
DEPLOY_PATH,
INJECT_SCSS,
2023-05-22 15:06:33 +08:00
LEGACY_MODE,
2024-07-25 16:30:30 +08:00
isCustomElement,
plugin,
define
})
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:
2023-01-31 19:17:38 +08:00
ws.send({ action: 'reload' })
break
2023-01-31 19:17:38 +08:00
}
} else if (act === 'unlink' || act === 'unlinkDir') {
2023-01-31 19:17:38 +08:00
ws.send({ action: 'reload' })
}
2023-01-30 19:11:03 +08:00
}
})
.on('ready', () => {
ready = true
})
2023-01-30 19:11:03 +08:00
})
2022-10-09 19:19:21 +08:00
}