import fs from 'iofs' import { join, resolve, dirname, parse } from 'path' import Es from 'esbuild' import { compileScss, parseJs, compileVue, parseHtml } from './compile-vue.js' const noc = Buffer.from('') export default function compile(root = '', dist = '', 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 let timeStart = Date.now() let template = fs.cat(join(process.env.PWD, 'index.html')).toString() let list = fs .ls(SOURCE_DIR, true) .map(it => ({ name: it.slice(SOURCE_DIR.length + 1), path: it, ext: parse(it).ext })) .filter(it => fs.isfile(it.path)) let compileFiles = function (currentPage, page, files) { for (let it of files) { // 入口文件, 特殊处理 if (page && it.path === page.entry) { let entry = fs.cat(page.entry).toString() entry = parseJs( entry, conf.imports, { IS_MPA, currentPage, IS_ENTRY: true, DEPLOY_PATH }, true ) let code = parseHtml( template, { page, imports: conf.imports, entry }, true ) fs.echo(code, join(dist, `${currentPage}.html`)) continue } console.log(' 解析 %s ...', it.name) switch (it.ext) { case '.vue': { let code = compileVue( it.path, conf.imports, { IS_MPA, currentPage, SOURCE_DIR, DEPLOY_PATH }, true ) Es.transform(code, { minify: true }).then(r => { fs.echo( r.code, join( dist, 'assets/js/', IS_MPA ? currentPage : '', it.name.replace(/\.vue$/, '.js') ) ) }) } break case '.js': { let code = fs.cat(it.path) code = parseJs( code + '', conf.imports, { IS_MPA, currentPage, DEPLOY_PATH }, true ) Es.transform(code, { minify: true }).then(r => { fs.echo( r.code, join(dist, 'assets/js/', IS_MPA ? currentPage : '', it.name) ) }) } break case '.scss': case '.css': { let code = compileScss(it.path) if (!it.name.startsWith('assets')) { it.name = 'assets/js/' + it.name } fs.echo(code, join(dist, it.name.replace(/\.scss$/, '.css'))) } break default: fs.cp(it.path, join(dist, it.name)) break } } } for (let currentPage in conf.pages) { let page = conf.pages[currentPage] let dir = dirname(page.entry) let files = [] fs.ls(dir, true).forEach(it => { if (fs.isdir(it)) { return } let idx = list.findIndex(_ => _.path === it) list.splice(idx, 1) files.push({ name: it.slice(dir.length + 1), path: it, ext: parse(it).ext }) }) console.log('正在生成 %s ...', `${currentPage}.html`) compileFiles(currentPage, page, files) } console.log('正在解析公共依赖 ...') compileFiles('', null, list) // if (fs.isdir(PUBLIC_DIR)) { console.log('正在处理静态资源 ...') fs.ls(PUBLIC_DIR, true).forEach(it => { if (fs.isfile(it)) { let name = it.slice(PUBLIC_DIR.length + 1) console.log(' 正在复制 %s ...', name) fs.cp(it, join(dist, name)) } }) } console.log('\n页面处理完成, 耗时 %ss\n', (Date.now() - timeStart) / 1000) }