UNPKG

2.71 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3'use strict'
4
5const fs = require('fs')
6const gulp = require('gulp')
7// 文件变动检测
8const chokidar = require('chokidar')
9// css压缩
10const minifier = require('sqwish')
11// js压缩
12const UglifyJS = require("uglify-js")
13// 日志输出
14const { getLogger } = require('log4js')
15const logger = getLogger()
16
17const heardHandle = require('./lib/heard')
18const bodyHandle = require('./lib/page')
19
20// 配置日志输出等级
21logger.level = 'debug'
22
23// 命令行运行目录
24const runPath = process.cwd()
25
26// 判断运行目录下是否包含配置文件
27if (!fs.readFileSync(`${runPath}/ozzx.json`)) {
28 logger.error('ozzx.json file does not exist!')
29 close()
30}
31
32// 读取配置文件
33const config = JSON.parse(fs.readFileSync(`${runPath}/ozzx.json`, 'utf8'))
34// 代码目录
35const path = runPath + config.root
36// 输出目录
37const outPutPath = `${runPath}/${config.outFolder}/`
38const corePath = `${__dirname}/core/`
39
40
41// 执行默认打包任务
42function pack () {
43 // 读取入口模板文件(一次性读取到内存中)
44 let templet = fs.readFileSync(`${path}/index.html`, 'utf8')
45 // 使用heard处理文件
46 templet = heardHandle(`${path}/${config.headFolder}/`, templet)
47
48 // 处理body
49 const dom = bodyHandle(templet, config)
50
51 // 读取出核心代码
52 const configData = `
53 window.ozzx = {
54 script: {}
55 };
56 var globalConfig = ${JSON.stringify(config)};
57 `
58 const coreData = configData + fs.readFileSync(`${corePath}main.js`, 'utf8')
59
60
61 // 读取出全局样式
62 const coreStyle = fs.readFileSync(`${path}/main.css`, 'utf8') + '\r\n'
63
64 // 判断是否需要压缩css
65 let outPutCss = coreStyle + dom.style
66 if (config.minifyCss) {
67 outPutCss = minifier.minify(outPutCss)
68 }
69
70 // 判断是否需要压缩js
71 let outPutJs = coreData + dom.script
72 if (config.minifyJs) {
73 outPutJs = UglifyJS.minify(outPutJs).code
74 }
75 // 判断输出目录是否存在,如果不存在则创建目录
76 if (!fs.existsSync(outPutPath)) {
77 fs.mkdirSync(outPutPath)
78 }
79 // 写出文件
80 fs.writeFileSync(`${outPutPath}main.css`, outPutCss)
81 fs.writeFileSync(`${outPutPath}main.js`, outPutJs)
82 fs.writeFileSync(`${outPutPath}index.html`, dom.html)
83 console.log('Package success!')
84}
85
86// 开始打包
87pack()
88
89// 判断是否开启文件变动自动重新打包
90if (config.autoPack) {
91 // 文件变动检测
92 const watcher = chokidar.watch(path, {
93 ignored: './' + config.outFolder + '/*',
94 persistent: true,
95 usePolling: true
96 })
97
98 watcher.on('change', path => {
99 console.log(`file change: ${path}`)
100 // 重新打包
101 pack()
102 })
103}