-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
77 lines (64 loc) · 1.89 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
75
76
77
var fs = require('fs');
var path = require('path');
var exts = ['.sass', '.scss'];
const exists = (file) => {
try {
fs.accessSync(file, fs.constants.F_OK);
return true;
} catch (e) {
return false;
}
}
const addPartialUnderscore = (file, ext) => {
const basename = path.basename(file, ext);
const partial = file.split(path.sep);
partial.splice(-1, 1, '_' + basename + ext);
return partial.join(path.sep);
}
const resolveImportPath = (file, ext) => {
const basename = path.basename(file);
const fullFile = file;
const isPartial = basename[0] === '_';
if (exists(file)) {
return file;
} else if (!isPartial) {
const partial = addPartialUnderscore(file, ext);
if (exists(partial)) return partial;
}
return '';
}
const end = (done) => (value) => {
return done ? done(value) : value;
}
module.exports = function(url, prev, done) {
done = end(done);
if (!url) return done(null);
const urlParts = url.split('/');
const packageName = urlParts[0];
const cwd = process.cwd();
try {
var packagePath = require.resolve(packageName, { paths: [cwd] });
} catch (e) {
return done(null);
}
const parts = packagePath.split(path.sep);
for (let i = parts.length; i >= 0; i--) {
if (parts[i] !== packageName || parts[i - 1] === packageName) continue;
const before = parts.splice(0, i + 1);
const after = urlParts.splice(1);
const resolved = [...before, ...after].join(path.sep);
const relative = path.relative(cwd, resolved);
const ext = path.extname(relative);
if (ext) {
const importPath = resolveImportPath(relative, ext);
if (importPath) return done({ file: importPath });
} else {
for (let j = 0; j < exts.length; j++) {
const importPath = resolveImportPath(relative + exts[j], exts[j]);
if (importPath) return done({ file: importPath });
}
}
break;
}
return done(null);
};