-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
62 lines (51 loc) · 1.84 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
'use strict';
const path = require('path');
/**
* @param {Object} options
* @param {String} options.dependency - The dependency name to resolve
* @param {String} options.filename - Filename that contains the dependency
* @param {String} options.directory - Root of all files
* @return {String} Absolute/resolved path of the dependency
*/
module.exports = function({ dependency, filename, directory } = {}) {
if (!dependency) throw new Error('dependency path not given');
if (!filename) throw new Error('filename not given');
if (!directory) throw new Error('directory not given');
const filepath = getDependencyPath(dependency, filename, directory);
const ext = getDependencyExtension(dependency, filename);
return filepath + ext;
};
/**
* @param {String} dependency
* @param {String} filename
* @param {String} directory
* @return {String} Absolute path for the dependency
*/
function getDependencyPath(dependency, filename, directory) {
if (dependency.startsWith('..') || dependency.startsWith('.')) {
return path.resolve(path.dirname(filename), dependency);
}
return path.resolve(directory, dependency);
}
/**
* @param {String} dependency
* @param {String} filename
* @return {String} The determined extension for the dependency (or empty if already supplied)
*/
function getDependencyExtension(dependency, filename) {
const depExt = path.extname(dependency);
const fileExt = path.extname(filename);
if (!depExt) {
return fileExt;
}
// If a dependency starts with a period AND it doesn't already end
// in .js AND doesn't use a custom plugin, add .js back to path
if (fileExt === '.js' && depExt !== '.js' && !dependency.includes('!')) {
return fileExt;
}
// If using a SystemJS style plugin
if (depExt.includes('!')) {
return depExt.substring(0, depExt.indexOf('!'));
}
return '';
}