forked from Brightspace/frau-sass-importer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (61 loc) · 1.53 KB
/
index.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
'use strict';
var path = require('path'),
fs = require('fs'),
resolve = require('resolve');
var handledBaseFolderNames = {
'bower_components': 'bower_components',
'node_modules': 'node_modules'
};
function customImporter(url, prev, done) {
if (!endsWith(url, '.scss')) {
url += '.scss';
}
try {
var resolvedNpmPath = resolveNpm(url, prev);
if (resolvedNpmPath) {
return complete({ file: resolvedNpmPath }, done);
}
} catch (e) { /* was not a node module */ }
var baseFolderName = url.split('/')[0];
if (handledBaseFolderNames[baseFolderName]) {
var result = findInParentDirSync(url, prev);
return complete(result, done);
} else {
return null;
}
}
function complete(result, done) {
if (isAsync(done)) {
done(result);
return;
}
return result;
}
function isAsync(doneCallback) {
return typeof doneCallback === 'function';
}
function endsWith(str, suffix) {
return str && str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function resolveNpm(id, referencingFile) {
return resolve.sync(id, {
basedir: path.dirname(referencingFile)
});
}
function findInParentDirSync(relativePath, startingDirPath) {
var dirToTry = path.join(startingDirPath, '..');
var pathToTry = path.join(dirToTry, relativePath);
try {
fs.accessSync(pathToTry, fs.R_OK);
return {
file: pathToTry
};
} catch (err) {
if (pathToTry === ('/' + relativePath)) {
return new Error('File not found: ' + relativePath);
} else {
return findInParentDirSync(relativePath, dirToTry);
}
}
}
module.exports = customImporter;