pinafore/bin/build-sass.js

71 lines
2.2 KiB
JavaScript
Raw Normal View History

2018-01-14 02:41:15 +01:00
#!/usr/bin/env node
const sass = require('node-sass')
const chokidar = require('chokidar')
const argv = require('yargs').argv
const path = require('path')
const debounce = require('lodash/debounce')
const fs = require('fs')
const pify = require('pify')
const writeFile = pify(fs.writeFile.bind(fs))
const readdir = pify(fs.readdir.bind(fs))
const readFile = pify(fs.readFile.bind(fs))
2018-01-14 02:41:15 +01:00
const render = pify(sass.render.bind(sass))
2018-01-14 03:59:49 +01:00
const now = require('performance-now')
2018-01-14 02:41:15 +01:00
const globalScss = path.join(__dirname, '../scss/global.scss')
const defaultThemeScss = path.join(__dirname, '../scss/themes/_default.scss')
const html2xxFile = path.join(__dirname, '../templates/2xx.html')
2018-01-14 02:41:15 +01:00
const scssDir = path.join(__dirname, '../scss')
const themesScssDir = path.join(__dirname, '../scss/themes')
const assetsDir = path.join(__dirname, '../assets')
function doWatch() {
2018-01-14 03:59:49 +01:00
var start = now()
2018-01-14 02:41:15 +01:00
chokidar.watch(scssDir).on('change', debounce(() => {
2018-01-14 03:59:49 +01:00
console.log('Recompiling SCSS...')
Promise.all([
compileGlobalSass(),
compileThemesSass()
]).then(() => {
console.log('Recompiled SCSS in ' + (now() - start) + 'ms')
})
2018-01-14 02:41:15 +01:00
}, 500))
chokidar.watch()
}
async function compileGlobalSass() {
let results = await Promise.all([
2018-01-14 23:54:20 +01:00
render({file: defaultThemeScss, outputStyle: 'compressed'}),
render({file: globalScss, outputStyle: 'compressed'})
2018-01-14 02:41:15 +01:00
])
let css = results.map(_ => _.css).join('')
2018-01-14 02:41:15 +01:00
let html = await readFile(html2xxFile, 'utf8')
html = html.replace(/<style>[\s\S]+?<\/style>/,
`<style>\n/* auto-generated w/ build-sass.js */\n${css}\n</style>`)
await writeFile(html2xxFile, html, 'utf8')
2018-01-14 02:41:15 +01:00
}
async function compileThemesSass() {
let files = (await readdir(themesScssDir)).filter(file => !path.basename(file).startsWith('_'))
await Promise.all(files.map(async file => {
let res = await render({file: path.join(themesScssDir, file)})
2018-01-14 03:59:49 +01:00
let outputFilename = 'theme-' + path.basename(file).replace(/\.scss$/, '.css')
await writeFile(path.join(assetsDir, outputFilename), res.css, 'utf8')
2018-01-14 02:41:15 +01:00
}))
}
async function main() {
await Promise.all([compileGlobalSass(), compileThemesSass()])
if (argv.watch) {
doWatch()
}
}
Promise.resolve().then(main).catch(err => {
console.error(err)
process.exit(1)
})