UNPKG

2.16 kBJavaScriptView Raw
1const path = require('path');
2const micromatch = require('micromatch');
3
4// Skip external modules. Based on http://git.io/pzPO.
5const internalModuleRegexp =
6 process.platform === 'win32'
7 ? /* istanbul ignore next */
8 /^(\.|\w:)/
9 : /^[/.]/;
10
11/**
12 * Module filters
13 */
14module.exports = {
15 internalOnly: internalModuleRegexp.test.bind(internalModuleRegexp),
16
17 /**
18 * Create a filter function for use with module-deps, allowing the specified
19 * external modules through.
20 *
21 * @param {Array<string>} indexes - the list of entry points that will be
22 * used by module-deps
23 * @param {Object} options - An options object with `external` being a
24 * micromatch-compatible glob. *NOTE:* the glob will be matched relative to
25 * the top-level node_modules directory for each entry point.
26 * @returns {function} - A function for use as the module-deps `postFilter`
27 * options.
28 */
29 externals: function externalModuleFilter(indexes, options) {
30 let externalFilters = false;
31 if (options.external) {
32 externalFilters = indexes.map(index => {
33 // grab the path of the top-level node_modules directory.
34 const topNodeModules = path.join(path.dirname(index), 'node_modules');
35 return function matchGlob(file, pkg) {
36 // if a module is not found, don't include it.
37 if (!file || !pkg) {
38 return false;
39 }
40 // if package.json specifies a 'main' script, strip that path off
41 // the file to get the module's directory.
42 // otherwise, just use the dirname of the file.
43 if (pkg.main) {
44 file = file.slice(0, -path.normalize(pkg.main).length);
45 } else {
46 file = path.dirname(file);
47 }
48 // test the path relative to the top node_modules dir.
49 const p = path.relative(topNodeModules, file);
50 return micromatch.any(p, options.external);
51 };
52 });
53 }
54
55 return function(id, file, pkg) {
56 const internal = internalModuleRegexp.test(id);
57 return (
58 internal || (externalFilters && externalFilters.some(f => f(file, pkg)))
59 );
60 };
61 }
62};