-
Notifications
You must be signed in to change notification settings - Fork 0
/
11tysass.ts
250 lines (222 loc) · 7.16 KB
/
11tysass.ts
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/// <reference types="sass" />
import chokidar from "chokidar"
import crypto from "crypto"
import { Logger } from "eazy-logger"
import fs from "fs-extra"
import debounce from "lodash.debounce"
import path from "path"
import sass from "sass"
import toHtml from "hast-util-to-html"
import { selectAll } from "hast-util-select"
import { shimPlugin } from "@henrycatalinismith/11tyshim"
import { rehypePlugin } from "@henrycatalinismith/11tyhype"
import { name, version, homepage } from "./package.json"
interface EleventyConfig {
addCollection: (name: string, fn: () => any) => void
addPlugin: (plugin: any, options: any) => void
}
interface PluginOptions {
files?: sass.Options[]
plugins?: ((css: string) => string)[]
verbose?: boolean
onInjectInline?: (css: string, html: string) => string | Promise<string>
}
export const sassPlugin = {
initArguments: {},
configFunction: function(
eleventyConfig: EleventyConfig,
options: PluginOptions,
) {
const logger = Logger({
prefix: `[{blue:${name}}@{blue:${version}}] `,
})
if (!options.verbose) {
logger.info = () => {}
}
if (!options || !options.files) {
logger.error("{red:error: nothing-to-render}")
logger.error("{red:missing a list of Sass files to render}")
logger.error("{red:for more details, see:}")
logger.error(`{red:${homepage}/#nothing-to-render}`)
process.exit(-1)
}
for (const file of options.files) {
if (!file.file) {
logger.error("{red:error: missing-file}")
logger.error("{red:missing `file` property on these Sass options}")
logger.error("{red:for more details, see:}")
logger.error(`{red:${homepage}/#missing-file}`)
process.exit(-1)
}
if (file.sourceMap === true && file.outFile) {
// Sass accepts a boolean true value for this parameter but that's not
// very useful here. So we convert these to a sensible string value.
file.sourceMap = `${file.outFile}.map`
}
}
const results: {
[name: string]: sass.Result
} = {}
options.files.forEach(file => {
results[file.file] = {
css: Buffer.from(""),
map: Buffer.from(""),
stats: {
entry: "",
includedFiles: [],
start: 0,
end: 0,
duration: 0,
}
}
})
function render(
file: sass.Options,
eleventyInstance: any
): sass.Result | void {
let result: sass.Result
try {
result = sass.renderSync(file)
} catch (e) {
logger.error("{red:error sass-error}")
e.formatted.split(/\n/).forEach((line: string) => {
logger.error(`{red:${line}}`)
})
logger.error("{red:for more details, see:}")
logger.error(`{red:${homepage}/#sass-error}`)
return
}
results[file.file] = result
let css = result.css.toString()
;(options.plugins || []).forEach(function(plugin) {
try {
css = plugin(css)
} catch(e) {
logger.error("{red:error: plugin-error}")
e.stack.split(/\n/).forEach((line: string) => {
logger.error(`{red:${line}}`)
})
logger.error("{red:for more details, see:}")
logger.error(`{red:${homepage}/#plugin-error}`)
}
})
results[file.file].css = Buffer.from(css)
logger.info([
`rendered {green:${result.stats.entry}}`,
`[{magenta:${result.stats.duration}ms}]`
].join(" "))
if (file.outFile) {
const outFileName = file.outFile.replace(
/\[hash\]/g,
crypto
.createHash("md5")
.update(css)
.digest("hex")
.slice(0, 8)
)
results[file.file].stats.entry = `/${outFileName}`
const outFilePath = path.join(
eleventyInstance.outputDir,
outFileName,
)
fs.ensureDirSync(path.dirname(outFilePath))
fs.writeFileSync(
outFilePath,
css,
)
logger.info(`wrote {green:${outFileName}}`)
}
if (file.sourceMap) {
const sourceMap = path.join(
eleventyInstance.outputDir,
file.sourceMap as string,
)
fs.writeFileSync(
sourceMap,
result.map.toString(),
)
logger.info(`wrote {green:${file.sourceMap}}`)
}
return result
}
let writeCount = 0
eleventyConfig.addPlugin(shimPlugin, {
write: (eleventyInstance: any) => {
options.files.forEach(function(file) {
const result = render(file, eleventyInstance)
if (!result && writeCount === 0) {
// The very first Sass render attempt has failed. For one-off
// builds this is fatal: the site isn't buildable. For dev server
// builds it's also unrecoverable as it stops us retrieving a list
// of included files to watch. So for both cases killing the
// process immediately is the only thing we can do to help the
// user. Doing so puts the Sass error message right at the end of
// the Eleventy output where it's most visible.
process.exit(-1)
}
writeCount += 1
})
},
serve: (eleventyInstance: any) => {
options.files.forEach(function(file) {
const chokidarPaths = results[file.file].stats.includedFiles
logger.info(`watching {magenta:${chokidarPaths.length}} files`)
const watcher = chokidar.watch(
chokidarPaths,
)
watcher.on(
"change",
debounce(
function() {
eleventyInstance.write()
eleventyInstance.eleventyServe.reload()
},
128,
)
)
})
},
verbose: options.verbose,
})
eleventyConfig.addPlugin(rehypePlugin, {
id: name,
plugins: [
[() => {
return async function(tree: any) {
const entries = Object.entries(results)
entries.forEach(([name, result]) => {
const selector = [
"link",
"[rel='stylesheet']",
`[href='${name}']`,
].join("")
const matches = selectAll(selector, tree)
matches.forEach((link: any) => {
link.properties.href = result.stats.entry
})
})
await Promise.all(entries.map(async ([name, result]) => {
const selector = [
"style",
`[data-src='${name}']`,
].join("")
const matches = selectAll(selector, tree)
await Promise.all(matches.map(async (style: any) => {
delete style.properties.dataSrc
let css = result.css.toString()
if (options.onInjectInline) {
css = await options.onInjectInline(css, toHtml(tree))
}
style.children = [{
type: "text",
value: css,
}]
}))
}))
}
}],
],
verbose: options.verbose,
})
}
}