/
SASSAsset.js
91 lines (78 loc) 路 2.55 KB
/
SASSAsset.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
90
91
const Asset = require('../Asset');
const localRequire = require('../utils/localRequire');
const promisify = require('../utils/promisify');
const path = require('path');
const os = require('os');
const Resolver = require('../Resolver');
class SASSAsset extends Asset {
constructor(name, options) {
super(name, options);
this.type = 'css';
}
async parse(code) {
// node-sass should be installed locally in the module that's being required
let sass = await localRequire('node-sass', this.name);
let render = promisify(sass.render.bind(sass));
const resolver = new Resolver({
extensions: ['.scss', '.sass'],
rootDir: this.options.rootDir
});
let opts =
(await this.getConfig(['.sassrc', '.sassrc.js'], {packageKey: 'sass'})) ||
{};
opts.includePaths = (opts.includePaths || []).concat(
path.dirname(this.name)
);
opts.data = opts.data ? opts.data + os.EOL + code : code;
let type = this.options.rendition ? this.options.rendition.type : path.extname(this.name).toLowerCase().replace('.','');
opts.indentedSyntax = typeof opts.indentedSyntax === 'boolean' ? opts.indentedSyntax : type === 'sass';
opts.functions = Object.assign({}, opts.functions, {
url: node => {
let filename = this.addURLDependency(node.getValue());
return new sass.types.String(`url(${JSON.stringify(filename)})`);
}
});
opts.importer = opts.importer || [];
opts.importer = Array.isArray(opts.importer) ? opts.importer : [opts.importer];
opts.importer.push((url, prev, done) => {
if (!/^(~|\.\/|\/)/.test(url)) {
url = './' + url;
} else if (!/^(~\/|\.\/|\/)/.test(url)) {
url = url.substring(1);
}
resolver
.resolve(url, prev === 'stdin' ? this.name : prev)
.then(resolved => resolved.path)
.catch(() => url)
.then(file => done({file}))
.catch(err => done(normalizeError(err)));
});
return await render(opts);
}
collectDependencies() {
for (let dep of this.ast.stats.includedFiles) {
this.addDependency(dep, {includedInParent: true});
}
}
generate() {
return [
{
type: 'css',
value: this.ast ? this.ast.css.toString() : '',
hasDependencies: false
}
];
}
}
module.exports = SASSAsset;
// Ensures an error inherits from Error
function normalizeError(err) {
let message = 'Unknown error';
if (err) {
if (err instanceof Error) {
return err;
}
message = err.stack || err.message || err;
}
return new Error(message);
}