1 | const postcss = require('postcss')
|
2 | const wxssPlugin = require('postcss-wxss')
|
3 | const fs = require('fs')
|
4 | const path = require('path')
|
5 |
|
6 | const importRegx = /@import\s+(?:'(.+\.wxss)'|"(.+\.wxss)");?/g
|
7 |
|
8 | let fileStack = []
|
9 |
|
10 | const constructPath = function (file) {
|
11 | const lastFile = fileStack.slice(-1)[0]
|
12 | let dir
|
13 | if (lastFile) {
|
14 | dir = path.dirname(lastFile)
|
15 | } else {
|
16 | dir = process.cwd()
|
17 | }
|
18 | const fullPath = path.resolve(dir, file)
|
19 |
|
20 | if (fileStack.indexOf(fullPath) === -1) {
|
21 | fileStack.push(fullPath)
|
22 | } else {
|
23 | throw new Error('Circular Import')
|
24 | }
|
25 | return fullPath
|
26 | }
|
27 |
|
28 | const getContent = function (file) {
|
29 | const content = fs.readFileSync(constructPath(file))
|
30 | return content.toString().replace(importRegx, function (str, p1, p2) {
|
31 | const childPath = p1 || p2
|
32 | const res = getContent(childPath)
|
33 | fileStack.pop()
|
34 | return res
|
35 | })
|
36 | }
|
37 |
|
38 | module.exports = function (files, opts) {
|
39 | fileStack = []
|
40 | const fileList = files.slice()
|
41 | const initFile = fileList.shift()
|
42 | const cssSource = getContent(initFile)
|
43 | return postcss([wxssPlugin(opts)])
|
44 | .process(cssSource)
|
45 | .then(res => res.css)
|
46 | .catch(err => console.log('postcss err:', err))
|
47 | }
|