-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsass-renderer.js
57 lines (45 loc) · 1.85 KB
/
sass-renderer.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
const fs = require('fs');
const path = require('path');
const util = require('util');
const sass = require('sass');
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);
const DEFAULT_OPTIONS = {
delim: /<%\s*content\s*%>/,
include: [path.resolve(process.cwd(), 'node_modules')],
template: path.resolve(__dirname, 'sass-template.tmpl'),
suffix: '-css.ts',
expandedOutput: false
};
module.exports = class SassRenderer {
constructor(options = {}) {
const settings = { ...DEFAULT_OPTIONS };
if (options.delim !== undefined) settings.delim = options.delim;
if (options.include !== undefined) settings.include = options.include;
if (options.template !== undefined) settings.template = options.template;
if (options.suffix !== undefined) settings.suffix = options.suffix;
if (options.expandedOutput !== undefined) settings.expandedOutput = options.expandedOutput;
Object.assign(this, settings);
}
async css(sassFile) {
const result = await sass.compileAsync(sassFile, {
loadPaths: this.include,
style: this.expandedOutput ? 'expanded' : 'compressed',
});
return result.css.trim().replace(/\\/g, "\\\\");
}
async render(source, output) {
const { delim, template, suffix } = this;
const tmp = await readFile(template, 'utf-8');
const match = delim.exec(tmp);
if (!match) {
throw new Error(`Template file ${template} did not contain template delimiters`);
}
const newContent = tmp.replace(delim, await this.css(source));
if (!output) {
output = `${source.split('.').slice(0, -1).join('.')}${suffix}`;
}
return writeFile(output, newContent, 'utf-8');
}
};
module.exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS;