cli/lib/main.js

94 lines
2.0 KiB
JavaScript
Raw Normal View History

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