-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
70 lines (56 loc) · 1.68 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
var fs = require('fs')
var util = require('util')
var path = require('path')
var assert = require('assert')
var postcss = require('postcss')
var Watcher = require('postcss-watcher')
var readFile = util.promisify(fs.readFile)
module.exports = middleware
function middleware (opts) {
opts = opts || {}
assert(!opts.plugin || Array.isArray(opts.plugins), 'koa-postcss-watch: opts.plugins must be an array')
var cache = {}
if (opts.file) cache[opts.file] = watch(opts.file, opts)
return async function (ctx, next) {
ctx.type = 'text/css'
if (opts.file) {
ctx.body = await cache[opts.file].processing
} else {
var file = path.resolve(opts.root || '', format(ctx.path))
if (!cache[file]) cache[file] = watch(file, opts)
ctx.body = await cache[file].processing
}
}
}
// start watching file and process on change
// (str, obj) -> obj
function watch (file, opts) {
var plugins = opts.plugins || []
var watcher = new Watcher(opts)
var bundle = postcss(plugins.concat(watcher.plugin()))
// ensure absolute file paths
if (!path.isAbsolute(file)) file = path.resolve(file)
var cache = {
file: file,
watcher: watcher,
processing: process(file, bundle)
}
cache.watcher.on('change', function () {
cache.processing = process(file, bundle)
})
return cache
}
// process file with bundle
// str -> Promise
function process (file, bundle) {
return readFile(file, 'utf8').then(function (content) {
return bundle.process(content, { from: file }).then(function (result) {
return result.css
})
})
}
// clean up request path as file path
// str -> str
function format (str) {
return str.replace(/^\//, '').replace(/\?.+$/, '')
}