Skip to content

Commit b8803f7

Browse files
committed
feat: support configurable options
feat: support main-overrides in config
1 parent 60eb3dd commit b8803f7

File tree

1 file changed

+45
-11
lines changed

1 file changed

+45
-11
lines changed

index.js

Lines changed: 45 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,58 @@
11
var fs = require('fs');
22

3-
const packageJsonPath = './package.json';
4-
const nodeModulesPath = './node_modules';
5-
const defaultMainFile = 'index.js';
3+
const defaultConfig = {
4+
packageJsonPath: './package.json',
5+
nodeModulesPath: './node_modules'
6+
};
67

7-
function getMainNodeFiles() {
8-
const packageJson = _getPackageJson(packageJsonPath);
8+
const defaultMainFile = 'index.js';
99

10-
return Object.keys(packageJson.dependencies)
11-
.map(key => _getMainPackageFile(`${nodeModulesPath}/${key}`));
10+
function getMainNodeFiles(options) {
11+
const config = Object.assign(defaultConfig, options);
12+
const packageJson = _getPackageJson(config.packageJsonPath);
13+
14+
var result = [];
15+
16+
if(!packageJson.dependencies) {
17+
return result;
18+
}
19+
20+
Object
21+
.keys(packageJson.dependencies)
22+
.forEach(key => {
23+
if(config.overrides && config.overrides[key]) {
24+
const overridenPaths = _getOverridenPaths(config, key);
25+
result.push.apply(result, overridenPaths);
26+
} else {
27+
var defaultMainPackageFile = _getMainPackageFile(`${config.nodeModulesPath}/${key}`);
28+
result.push(defaultMainPackageFile);
29+
}
30+
});
31+
32+
return result;
1233
}
1334

1435
function _getMainPackageFile(modulePath) {
15-
var packageJson = _getPackageJson(modulePath + '/package.json');
16-
return modulePath + "/" + (packageJson.main || defaultMainFile);
36+
var packageJson = _getPackageJson(`${modulePath}/package.json`);
37+
return `${modulePath}/${packageJson.main || defaultMainFile}`;
1738
}
1839

1940
function _getPackageJson(path) {
20-
const file = fs.readFileSync(path);
21-
return JSON.parse(file.toString());
41+
const file = fs.readFileSync(path);
42+
if(!file) {
43+
throw new Error('package.json not found');
44+
}
45+
46+
return JSON.parse(file.toString());
47+
}
48+
49+
function _getOverridenPaths(config, key) {
50+
const mainOverrides = config.overrides[key];
51+
if(Array.isArray(mainOverrides)) {
52+
return mainOverrides.map(path => `${config.nodeModulesPath}/${key}/${path}`);
53+
} else {
54+
return [`${config.nodeModulesPath}/${key}/${mainOverrides}`];
55+
}
2256
}
2357

2458
module.exports = getMainNodeFiles;

0 commit comments

Comments
 (0)