import http from 'http' import https from 'https' import fs from 'iofs' import { join, resolve, dirname } from 'path' import { parse } from 'url' import socket from './ws.js' import chokidar from 'chokidar' import { red, cyan, blue } from 'kolorist' 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 = {} const CACHE = {} //文件缓存, 用于hmr 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' if (USE_HTTPS) { Object.assign(SERVER_OPTIONS, conf.devServer.ssl) if (!SERVER_OPTIONS.key || !SERVER_OPTIONS.cert) { console.error('证书错误: https 证书不能为空!!!\n') process.exit(1) } } 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 `
  • ${tmp}
  • ` }) .join('') let ready = false let pagesDir = '', currentPage = '' server .on('request', function (req, res) { let pathname = parse(req.url.slice(1)).pathname let pageName = '', isIndex = false // 是否渲染目录页 let ext if (pathname) { pathname = pathname.split('/') if (pathname[0].endsWith('.html')) { pageName = pathname.shift() let tmp = pageName.split('.') ext = tmp.pop() pageName = tmp.join('.') 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('/') } else { if (IS_MPA) { isIndex = true } else { pageName = Object.keys(conf.pages).pop() currentPage = pageName pagesDir = dirname(conf.pages[pageName].entry) ext = 'html' } } // 修正history路由时的访问 if (pathname === ext) { 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, 'OK') res.end('') } 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 }) code = parseHtml(html, { page, imports: conf.imports, entry }) } break case 'vue': { let rpath = pathname.replace(/^assets\/js\//, '') let file if (IS_MPA) { file = join(pagesDir, rpath) } else { file = join(root, rpath) } if (!fs.isfile(file)) { console.clear() console.log(cyan(rpath), red(`not found!!!`)) console.log( red( '请正确填写引入的文件路径, vue-live 不再自动补全【%s】\n' ), blue('/index.vue') ) } code = compileVue(file, conf.imports, { IS_MPA, currentPage, root, pagesDir, CACHE }) res.setHeader('content-type', MIME_TYPES.js) } break case 'scss': case 'css': { let file = join( root, pathname .replace(/^assets\/css\//, '') .replace(/^assets\/js\//, '') ) code = compileScss(file) res.setHeader('content-type', MIME_TYPES.css) } break case 'js': { pathname = pathname.replace(/^assets\/js\//, '') let file if (pathname.startsWith(currentPage)) { file = join(pagesDir, pathname) } else { file = join(root, pathname) } if (fs.isfile(file)) { code = fs.cat(file) } else { console.clear() console.log(cyan(pathname), red(`not found!!!`)) console.log( red( '请正确填写引入的文件路径, vue-live 不再自动补全【%s】\n' ), blue('/index.js') ) } code = parseJs(code + '', conf.imports, { IS_MPA, currentPage }) res.setHeader('content-type', MIME_TYPES.js) } break case 'png': case 'jpg': case 'jpeg': case 'webp': case 'gif': case 'svg': case 'ico': case 'bmp': res.setHeader('content-type', MIME_TYPES[ext]) code = fs.cat(join(root, pathname)) if (code === null) { console.error(pathname, '文件不存在') res.writeHead(404, 'Not Found') res.end('') return } break default: res.setHeader('content-type', MIME_TYPES[ext] || MIME_TYPES.html) break } res.setHeader('content-length', Buffer.byteLength(code || noc)) res.writeHead(200, 'OK') res.end(code || noc) } }) .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', USE_HTTPS ? 'https' : 'http', '127.0.0.1', PORT ) console.log( ' 外网: %s://%s:%d\n', USE_HTTPS ? 'https' : 'http', DOMAIN, PORT ) }) chokidar .watch([root, join(root, '../index.html')]) .on('all', (act, filePath) => { if (ready) { let file = filePath.slice(root.length) if (act === 'add' || act === 'change') { let ext = file.slice(file.lastIndexOf('.') + 1) switch (ext) { case 'css': case 'scss': { 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, root, pagesDir, CACHE }) 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' }) break } } else if (act === 'unlink' || act === 'unlinkDir') { ws.send({ action: 'reload' }) } } }) .on('ready', () => { ready = true }) }