Last active
September 21, 2017 09:08
-
-
Save lsongdev/ea88f132ddd3a0cff600a6317b014cad to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const path = require('path'); | |
const resolve = require('resolve'); | |
const rImport = /import\s+(.+)\s+from\s+['"]([^'"]+)['"]/; | |
const rRequire = /require\s*\(['"]([^'")]+)['"]\)/; | |
const parseDeps = name => { | |
return fs.readFileSync(name, 'utf8') | |
.replace(/\/\*[\s\S]*?\*\//g, '') // block-comment | |
.replace(/(import.*)(\{[\s\S]+\})(.*from)/gm, (m, $1, $2, $3) => { | |
return $1 + $2.replace(/\n/g, '') + $3; | |
}) | |
.split('\n') | |
.map(line => { | |
if (/^\s*\/\//.test(line)) // line-comment | |
return null; | |
if (rImport.test(line)) { | |
return rImport.exec(line)[2]; | |
} | |
if (rRequire.test(line)) { | |
return rRequire.exec(line)[1]; | |
} | |
return null; | |
}) | |
.filter(Boolean) | |
.map(mod => { | |
return resolve.sync(mod, { | |
basedir: path.dirname(name), | |
extensions: [ '.js', '.jsx', '.es6' ] | |
}); | |
}); | |
}; | |
const findDeps = (name) => { | |
let f; // file name | |
const c = {}; // cache | |
const d = []; // deps | |
const q = [ name ]; // pending queue | |
while (f = q.pop()) { // eslint-disable-line | |
d.push(f); | |
if (!c[f]) { | |
c[f] = parseDeps(f); | |
} | |
if (c[f]) { | |
q.push.apply(q, c[f]); // eslint-disable-line | |
} | |
} | |
return d.filter((p, i) => d.indexOf(p) === i); | |
}; | |
console.log(findDeps('./client/pages/index.jsx')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment