UNPKG

1.94 kBJavaScriptView Raw
1var child = require("child_process");
2var fs = require("fs");
3var kebabCase = require("lodash.kebabcase");
4var path = require("path");
5var util = require("util");
6
7module.exports.check = function(dependencies, dirs) {
8 var missing = [];
9 dependencies.forEach(function(dependency) {
10 // Ignore relative modules, which aren't installed by NPM
11 if (/^\./.test(dependency)) {
12 return;
13 }
14
15 // Only look for the dependency directory
16 dependency = dependency.split('/')[0];
17
18 // Bail early if we've already determined this is a missing dependency
19 if (missing.indexOf(dependency) !== -1) {
20 return;
21 }
22
23 try {
24 // Ignore dependencies that are resolveable
25 require.resolve(dependency);
26
27 return;
28 } catch(e) {
29 var modulePaths = (dirs || []).map(function(dir) {
30 return path.resolve(dir, dependency);
31 });
32
33 // Check all module directories for dependency directory
34 while (modulePaths.length) {
35 var modulePath = modulePaths.shift();
36
37 try {
38 // If it exists, Webpack can find it
39 fs.statSync(modulePath);
40
41 return;
42 } catch(e) {}
43 }
44
45 // Dependency must be missing
46 missing.push(dependency);
47 }
48 });
49 return missing;
50}
51
52module.exports.install = function install(dependencies, options) {
53 if (!dependencies || !dependencies.length) {
54 return undefined;
55 }
56
57 var args = ["install"].concat(dependencies);
58
59 if (options) {
60 for (option in options) {
61 var arg = util.format("--%s", kebabCase(option));
62 var value = options[option];
63
64 if (value === false) {
65 continue;
66 }
67
68 if (value === true) {
69 args.push(arg);
70 } else {
71 args.push(util.format("%s='%s'", arg, value));
72 }
73 }
74 }
75
76 console.info("Installing missing dependencies %s...", dependencies.join(" "));
77
78 return child.spawnSync("npm", args, { stdio: "inherit" });
79};