forked from GoogleChrome/web.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompile-css.js
More file actions
89 lines (78 loc) · 2.49 KB
/
compile-css.js
File metadata and controls
89 lines (78 loc) · 2.49 KB
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 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('dotenv').config();
const isProd = process.env.ELEVENTY_ENV === 'prod';
const fs = require('fs');
const path = require('path');
const log = require('fancy-log');
const sassEngine = (function() {
try {
// node-sass is faster, but regularly fails to install correctly (native bindings)
return require('node-sass');
} catch (e) {
// fallback to the official transpiled version
return require('sass');
}
})();
/**
* @param {string} input filename to read for input
* @param {string} output filename to use for output (but does not write)
* @return {{css: !Buffer, map: !Buffer}}
*/
function compileCSS(input, output) {
fs.mkdirSync(path.dirname(output), {recursive: true});
// #1: Compile CSS with either engine.
const compiledOptions = {
file: input,
outFile: output,
sourceMap: true,
omitSourceMapUrl: true, // since we just read it from the result object
};
if (isProd) {
compiledOptions.outputStyle = 'compressed';
}
log('Compiling', input);
const compiledResult = sassEngine.renderSync(compiledOptions);
if (!isProd) {
return compiledResult;
}
// nb. Only require() dependencies for autoprefixer when used.
const autoprefixer = require('autoprefixer');
const postcss = require('postcss');
// #2: Run postcss for autoprefixer.
const postcssOptions = {
from: output,
to: output,
map: {
prev: JSON.parse(compiledResult.map.toString()),
annotation: true,
},
};
log('Running postcss (autoprefixer)...');
const postcssResult = postcss([autoprefixer]).process(
compiledResult.css.toString(),
postcssOptions,
);
postcssResult.warnings().forEach((warn) => {
console.warn(warn.toString());
});
return postcssResult;
}
const target = process.argv[3] || 'out.css';
const out = compileCSS(process.argv[2], target);
fs.writeFileSync(target, out.css);
fs.writeFileSync(target + '.map', out.map);
log('Finished CSS!');