fite/lib/dev.js

325 lines
9.1 KiB
JavaScript
Raw Normal View History

2022-10-09 19:19:21 +08:00
import http from 'http'
2022-10-19 17:41:50 +08:00
import https from 'https'
2022-10-09 19:19:21 +08:00
import fs from 'iofs'
2022-10-10 15:05:30 +08:00
import { join, resolve, dirname } from 'path'
2022-10-09 19:19:21 +08:00
import { parse } from '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'
2023-02-01 10:51:33 +08:00
import { red, cyan, blue } from 'kolorist'
2022-10-09 19:19:21 +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('')
2022-10-19 17:41:50 +08:00
const SERVER_OPTIONS = {}
2023-01-31 19:17:38 +08:00
const CACHE = {} //文件缓存, 用于hmr
2022-10-09 19:19:21 +08:00
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-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')
process.exit(1)
}
}
2023-01-17 18:43:05 +08:00
const server = (USE_HTTPS ? https : http)
.createServer(SERVER_OPTIONS)
.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
.on('request', function (req, res) {
2023-02-19 16:52:55 +08:00
let url =
DEPLOY_PATH && req.url.startsWith(DEPLOY_PATH.replace(/\/$/, ''))
? 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
2023-01-17 18:43:05 +08:00
if (pathname) {
pathname = pathname.split('/')
2022-10-10 15:05:30 +08:00
2023-01-17 18:43:05 +08:00
if (pathname[0].endsWith('.html')) {
pageName = pathname.shift()
2022-10-10 15:05:30 +08:00
2023-01-17 18:43:05 +08:00
let tmp = pageName.split('.')
2022-10-19 17:41:50 +08:00
2023-01-17 18:43:05 +08:00
ext = tmp.pop()
pageName = tmp.join('.')
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) {
ext = pathname.at(-1).split('.').pop()
pageName = currentPage
} else {
pageName = Object.keys(conf.pages).pop()
currentPage = pageName
pagesDir = dirname(conf.pages[pageName].entry)
ext = 'html'
}
}
pathname = pathname.join('/')
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
}
2023-01-17 18:43:05 +08:00
// 修正history路由时的访问
if (pathname === ext) {
ext = 'html'
}
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)
res.writeHead(200, 'OK')
res.end('<ul>' + indexPage + '</ul>')
} 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()
let html = fs.cat(join(process.cwd(), 'index.html')).toString()
2022-10-11 19:31:04 +08:00
2023-02-12 23:01:57 +08:00
entry = parseJs(entry, conf.imports, {
IS_MPA,
currentPage,
2023-02-19 16:52:55 +08:00
IS_ENTRY: true,
DEPLOY_PATH
2023-02-12 23:01:57 +08:00
})
2022-10-11 19:31:04 +08:00
2023-01-17 18:43:05 +08:00
code = parseHtml(html, { page, imports: conf.imports, entry })
}
2022-10-09 19:19:21 +08:00
2023-01-17 18:43:05 +08:00
break
case 'vue':
{
let rpath = pathname.replace(/^assets\/js\//, '')
let file
if (IS_MPA) {
file = join(pagesDir, rpath)
} 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-02-01 10:51:33 +08:00
console.clear()
console.log(cyan(rpath), red(`not found!!!`))
console.log(
red(
'请正确填写引入的文件路径, vue-live 不再自动补全【%s】\n'
),
blue('/index.vue')
)
2023-01-17 18:43:05 +08:00
}
code = compileVue(file, conf.imports, {
IS_MPA,
currentPage,
2023-02-16 15:32:17 +08:00
SOURCE_DIR,
2023-01-31 19:17:38 +08:00
pagesDir,
2023-02-19 16:52:55 +08:00
CACHE,
DEPLOY_PATH
2023-01-17 18:43:05 +08:00
})
2023-01-31 19:17:38 +08:00
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':
{
2023-01-31 19:17:38 +08:00
let file = join(
2023-02-16 15:32:17 +08:00
SOURCE_DIR,
2023-01-31 19:17:38 +08:00
pathname
.replace(/^assets\/css\//, '')
.replace(/^assets\/js\//, '')
)
2023-01-17 18:43:05 +08:00
code = compileScss(file)
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':
{
pathname = pathname.replace(/^assets\/js\//, '')
let file
if (pathname.startsWith(currentPage)) {
file = join(pagesDir, pathname)
} else {
2023-02-16 15:32:17 +08:00
file = join(SOURCE_DIR, pathname)
2023-01-17 18:43:05 +08:00
}
if (fs.isfile(file)) {
code = fs.cat(file)
2023-02-16 19:29:49 +08:00
} else if (fs.isfile(join(PUBLIC_DIR, pathname))) {
code = fs.cat(join(PUBLIC_DIR, pathname))
2023-01-17 18:43:05 +08:00
} else {
2023-02-01 10:51:33 +08:00
console.clear()
console.log(cyan(pathname), red(`not found!!!`))
console.log(
red(
'请正确填写引入的文件路径, vue-live 不再自动补全【%s】\n'
),
blue('/index.js')
)
2023-01-17 18:43:05 +08:00
}
2023-02-19 16:52:55 +08:00
code = parseJs(code + '', conf.imports, {
IS_MPA,
currentPage,
DEPLOY_PATH
})
2023-01-17 18:43:05 +08:00
res.setHeader('content-type', MIME_TYPES.js)
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)
2023-02-16 15:32:17 +08:00
if (fs.isfile(join(PUBLIC_DIR, pathname))) {
code = fs.cat(join(PUBLIC_DIR, pathname))
2023-02-16 19:29:49 +08:00
} else if (fs.isfile(join(SOURCE_DIR, pathname))) {
code = fs.cat(join(SOURCE_DIR, pathname))
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-02-16 19:29:49 +08:00
console.clear()
console.log(cyan(pathname), red(`not found!!!`))
2023-01-17 18:43:05 +08:00
res.writeHead(404, 'Not Found')
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-01-17 18:43:05 +08:00
res.setHeader('content-length', Buffer.byteLength(code || noc))
res.writeHead(200, 'OK')
res.end(code || noc)
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
2023-02-16 15:32:17 +08:00
createServer(SOURCE_DIR, 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',
'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
)
2022-10-09 19:19:21 +08:00
})
2023-01-17 18:43:05 +08:00
2023-01-30 19:11:03 +08:00
chokidar
2023-02-16 19:29:49 +08:00
.watch([SOURCE_DIR, PUBLIC_DIR, join(root, './index.html')])
2023-01-31 19:17:38 +08:00
.on('all', (act, filePath) => {
2023-01-30 19:11:03 +08:00
if (ready) {
2023-02-16 15:32:17 +08:00
let file = filePath.slice(SOURCE_DIR.length)
2023-01-31 19:17:38 +08:00
2023-01-30 19:11:03 +08:00
if (act === 'add' || act === 'change') {
let ext = file.slice(file.lastIndexOf('.') + 1)
switch (ext) {
case 'css':
case 'scss':
2023-01-31 19:17:38 +08:00
{
let content = fs.cat(filePath).toString()
ws.send({ action: 'render', data: { path: file, content } })
}
break
case 'vue':
{
let content = compileVue(filePath, conf.imports, {
IS_MPA,
currentPage,
2023-02-16 15:32:17 +08:00
SOURCE_DIR,
2023-01-31 19:17:38 +08:00
pagesDir,
2023-02-19 16:52:55 +08:00
CACHE,
DEPLOY_PATH
2023-01-31 19:17:38 +08:00
})
let tmp = CACHE[filePath]
if (tmp.changed) {
ws.send({ action: 'reload' })
} else {
ws.send({
action: 'render',
data: { path: file, content: tmp.css }
})
}
}
break
default:
ws.send({ action: 'reload' })
2023-01-30 19:11:03 +08:00
break
}
2023-01-31 19:17:38 +08:00
} else if (act === 'unlink' || act === 'unlinkDir') {
ws.send({ action: 'reload' })
2023-01-30 19:11:03 +08:00
}
}
})
.on('ready', () => {
ready = true
})
2022-10-09 19:19:21 +08:00
}