UNPKG

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