cli/lib/main.js

80 lines
1.9 KiB
JavaScript
Raw Normal View History

2023-03-14 15:39:00 +08:00
import fs from 'iofs'
import { join, resolve, dirname, parse } from 'path'
import Es from 'esbuild'
import chokidar from 'chokidar'
import { red, blue } from 'kolorist'
import { compileScss } from './utils.js'
const noc = Buffer.from('')
export default function compile(root = '', isProd = false, es) {
//
const SOURCE_DIR = join(root, 'src')
const DIST_DIR = join(root, 'dist')
const OPTIONS = {
target: es || 'esnext',
minify: isProd,
format: 'esm'
}
if (isProd) {
fs.rm(DIST_DIR, true)
}
2023-03-23 14:34:43 +08:00
let ready = false
2023-03-14 15:39:00 +08:00
chokidar
.watch(SOURCE_DIR)
.on('all', (act, filePath) => {
2023-03-15 11:20:53 +08:00
let file = filePath.slice(SOURCE_DIR.length)
let target = join(DIST_DIR, file)
2023-03-14 15:39:00 +08:00
2023-03-23 14:34:43 +08:00
if (ready) {
console.clear()
}
2023-03-15 11:20:53 +08:00
if (act === 'add' || act === 'change') {
let ext = file.slice(file.lastIndexOf('.') + 1)
2023-03-14 15:39:00 +08:00
2023-03-15 11:20:53 +08:00
switch (ext) {
case 'css':
case 'jpg':
case 'png':
case 'svg':
case 'json':
case 'gif':
case 'webp':
console.log('复制 %s ...', blue(file))
fs.cp(filePath, target)
break
2023-03-14 15:39:00 +08:00
2023-03-15 11:20:53 +08:00
case 'js':
{
let code = fs.cat(filePath).toString()
console.log('编译 %s ...', blue(file))
2023-03-23 14:33:20 +08:00
try {
code = Es.transformSync(code, OPTIONS).code
} catch (err) {
console.log('compile scss: ', file)
console.error(err)
}
2023-03-14 15:39:00 +08:00
2023-03-23 14:33:20 +08:00
code = code.replace(/css`([\w\W]*?)`/g, function (m, scss) {
scss = compileScss(scss)
return `css\`${scss}\``
})
2023-03-15 11:20:53 +08:00
fs.echo(code, target)
}
break
2023-03-14 15:39:00 +08:00
}
}
})
.on('ready', () => {
2023-03-23 14:34:43 +08:00
console.clear()
ready = true
2023-03-14 15:39:00 +08:00
if (isProd) {
process.exit()
}
})
}