-
Notifications
You must be signed in to change notification settings - Fork 0
/
eleventy-plugin-css.js
78 lines (62 loc) · 1.91 KB
/
eleventy-plugin-css.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
const postcss = require('postcss')
/**
* @callback PluginFilter
* @param {string} inputContent
* @param {string} inputPath
*/
/**
* @typedef {Object} PluginOptions
* @property {Array<import('postcss').AcceptedPlugin>} [postcssPlugins]
* @property {PluginFilter} filter
*/
module.exports = function(eleventyConfig, /**@type {PluginOptions}*/ pluginOptions = {}) {
const postcssPlugins = pluginOptions.postcssPlugins
?? [
require('postcss-import'),
require('autoprefixer'),
process.env.NODE_ENV === 'production' && require('postcss-csso'),
].filter(Boolean)
async function processStyles({ source, options, plugins = postcssPlugins }) {
const opts = {
from: undefined,
...options
}
const result = await postcss(plugins).process(source, opts)
return result
}
eleventyConfig.addFilter('processStyles', async function(source, options) {
const cssOutput = await processStyles({ source, options })
return cssOutput.css
})
eleventyConfig.addTemplateFormats('css')
eleventyConfig.addExtension('css', {
read: true,
encoding: 'utf-8',
outputFileExtension: 'css',
compileOptions: {
permalink(inputContent, inputPath) {
return function(data) {
return data.permalink
}
}
},
async compile(inputContent, inputPath) {
if (typeof pluginOptions.filter === 'function' && !pluginOptions.filter(inputContent, inputPath)) {
return
}
const result = await processStyles({
source: inputContent,
options: {
from: inputPath
}
})
const dependencies = (result.messages ?? [])
.filter((message) => message.type === 'dependency' && message.plugin === 'postcss-import')
.map((message) => message.file)
this.addDependencies(inputPath, dependencies)
return async function(data) {
return result.css
}
}
})
}