This repository has been archived by the owner on Apr 26, 2023. It is now read-only.
/
postcss.js
78 lines (68 loc) · 2.17 KB
/
postcss.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
71
72
73
74
75
76
77
78
import path from 'path'
import tools from 'browserify-transform-tools'
import postcss from 'postcss'
import postcssImport from 'postcss-import'
import postcssModules from 'postcss-modules'
import resolve from 'resolve'
import minimatch from 'minimatch'
import MemoryFS from 'memory-fs'
import Clean from 'clean-css'
import { CONFIG } from '../utils/config'
import { addToDepTree } from '../utils/deptree'
const fs = new MemoryFS()
const cssModulesPlugin = postcssModules({
getJSON (cssFilename, json) {
fs.mkdirpSync(path.dirname(cssFilename))
fs.writeFileSync(cssFilename, json)
}
})
export default tools.makeStringTransform('postcss', {
includeExtensions: CONFIG.postcss.extensions
}, async (content, opts, done) => {
try {
const options = { from: opts.file }
const plugins = [
postcssImport({
path: [
CONFIG.sourceDir,
path.dirname(opts.file),
path.resolve(process.cwd(), 'node_modules')
],
onImport: (files) => {
files.forEach((f) => {
if (f !== opts.file) addToDepTree(f, opts.file)
})
}
})
]
if (CONFIG.postcss.modules) {
plugins.push(cssModulesPlugin)
}
CONFIG.postcss.parsers.forEach((p) => {
if (typeof p === 'object') {
if (minimatch(opts.file, p.match)) {
options.parser = require(resolve.sync(p.name, { basedir: process.cwd() }))
}
} else if (typeof p === 'string') {
options.parser = require(resolve.sync(p, { basedir: process.cwd() }))
}
})
CONFIG.postcss.plugins.forEach((p) => {
if (typeof p === 'object') {
plugins.push(require(resolve.sync(p.name, { basedir: process.cwd() }))(p.options || {}))
} else {
plugins.push(require(resolve.sync(p, { basedir: process.cwd() })))
}
})
const res = await postcss(plugins).process(content, options)
const css = new Clean().minify(res.css).styles
let outputJs = `_INSERT_CSS_("${css}");`
if (CONFIG.postcss.modules) {
const json = fs.readFileSync(opts.file)
outputJs += `module.exports = ${JSON.stringify(json)};`
}
done(null, outputJs)
} catch (err) {
done(err)
}
})