Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0e4c439

Browse files
committed
create detectImports
1 parent 76271ce commit 0e4c439

File tree

3 files changed

+36
-7
lines changed

3 files changed

+36
-7
lines changed

lib/detectImports.js

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,38 @@
1-
const import = /\bimport\s+(?:.+\s+from\s+)?[\'"]([^"\']+)["\']/;
1+
const importRegex = /\bimport\s+(?:\s?(.+)\}?\s+from\s+)?[\'"]([^"\']+)["\']/;
2+
const namedRegex = /^{.+}$/;
3+
4+
let imports = {};
25

36
// detects imports
47
// adds imports to global scope of rewired object
5-
function detectImports(file) {
8+
function detectImports(src) {
9+
src.split('\n').forEach(line => {
10+
const match = line.match(importRegex);
11+
let vars = null;
12+
let path = null;
13+
if (match) {
14+
vars = match[1];
15+
vars = vars.match(namedRegex) ? vars.slice(1, -1) : vars;
16+
vars = vars.split(',').map(x => x.trim());
17+
path = match[2];
18+
}
19+
// add to array of imports
20+
if (vars && vars.length) {
21+
vars.forEach(i => imports[i] = path);
22+
}
23+
});
24+
25+
for (key in imports) { /* jshint forin: false */
26+
let value = imports[key];
27+
28+
// key may be an invalid variable name (e.g. 'a-b')
29+
try {
30+
// eval(`var ${key};`);
31+
src += `var ${key}`;
32+
} catch(e) {}
33+
}
634

35+
return src;
736
}
837

938
module.exports = detectImports;

lib/fileExists.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,8 @@ var fs = require('fs');
22

33
function fileExists(path) {
44
try {
5-
fs.accessSync(path, fs.F_OK);
6-
}
7-
catch (e) {
5+
fs.accessSync(path, fs.F_OK);
6+
} catch (e) {
87
if (e) {
98
console.log(e);
109
}

lib/getImportGlobalsSrc.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
const detectImports = require('./detectImports');
12
/**
23
* Declares all globals with a var and assigns the global object. Thus you're able to
34
* override globals without changing the global object itself.
@@ -25,7 +26,7 @@ function getImportGlobalsSrc(ignore) {
2526
if (ignore.indexOf(key) !== -1) {
2627
continue;
2728
}
28-
value = globalObj[key];
29+
// value = globalObj[key];
2930

3031
// key may be an invalid variable name (e.g. 'a-b')
3132
try {
@@ -34,7 +35,7 @@ function getImportGlobalsSrc(ignore) {
3435
} catch(e) {}
3536
}
3637

37-
return src;
38+
return detectImports(src);
3839
}
3940

4041
module.exports = getImportGlobalsSrc;

0 commit comments

Comments
 (0)