-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
89 lines (77 loc) · 2.6 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright (c) 2016-present, salesforce.com, inc. All rights reserved
// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license
const _ = require('lodash')
const fs = require('fs')
const path = require('path')
const IMPORT_PATTERN = /(@import)([\s\S]*?);/g
const parseImports = (chunk) => _(chunk)
.split(',')
.flatMap(c => c.split('\n'))
.map(_.trim)
.map(c => c.match(/('|")(.+?)('|")/))
.compact()
.filter(c => /^("|')/.test(c.input))
.map(match => match[2])
.value()
const getSearchPaths = (entry, importPath, includePaths) => {
const ext = /\.scss$/.test(importPath) ? '' : '.scss'
const searchDirectories = [path.dirname(entry)].concat(includePaths)
return _(searchDirectories).flatMap(directory => {
return ['', '_'].map(prefix => {
const parsed = path.parse(path.join(directory, `${importPath}${ext}`))
parsed.base = `${prefix}${parsed.base}`
return path.format(parsed)
})
}).value()
}
const flattenImports = (imports) => _.flatMapDeep(imports, imports => {
return _.map(imports, (imports, key) => {
return flattenImports(imports).concat(key)
})
})
const inlineImports = (entry, options) => {
options = _.defaults({}, options, {
comments: false,
includePaths: []
})
const replaceImports = (entry, imports) =>
(match, keyword, chunk) =>
parseImports(chunk)
.map(importPath => {
const searchPaths = getSearchPaths(entry, importPath, options.includePaths)
let foundSearchPath = false
for (const searchPath of searchPaths) {
try {
fs.accessSync(searchPath)
foundSearchPath = searchPath
} catch (e) {}
}
if (foundSearchPath) {
const comments = options.comments ? [
'================================================',
`// ${foundSearchPath}`,
'================================================'
] : []
const nextImports = []
imports.push({ [foundSearchPath]: nextImports })
return comments
.concat(walk(foundSearchPath, nextImports))
.join('\n')
}
throw new Error(`@import not found: "${importPath}" in "${entry}"`)
})
.join('\n')
const walk = (entry, imports) => fs
.readFileSync(entry, 'utf-8')
.replace(IMPORT_PATTERN, replaceImports(entry, imports))
const imports = [{
[entry]: []
}]
const scss = walk(entry, imports[0][entry])
return {
scss,
imports: imports,
importsFlattened: flattenImports(imports)
}
}
module.exports = inlineImports