Skip to content

Instantly share code, notes, and snippets.

@alinz
Last active November 16, 2017 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alinz/b2242c5ce93ff1981be9da6af37def9b to your computer and use it in GitHub Desktop.
Save alinz/b2242c5ce93ff1981be9da6af37def9b to your computer and use it in GitHub Desktop.
Dependency Tracker for your app using babel
// @flow
// make sure to install `yarn add babel-preset-stage-0`
const fs = require('fs')
const path = require('path')
const { transform } = require('babel-core')
const walker = (inputPath, extension, list = []) => {
if (fs.statSync(inputPath).isFile()) {
list.push(inputPath)
return
}
fs.readdirSync(inputPath).forEach(target => {
const src = path.join(inputPath, target)
const stat = fs.statSync(src)
if (stat.isDirectory()) {
walker(src, extension, list)
} else {
if (src.endsWith(extension)) {
list.push(src)
}
}
})
}
const getAllImports = filepath => {
const imports = []
const content = fs.readFileSync(filepath)
transform(content, {
plugins: [
//'transform-runtime',
//'transform-react-jsx',
//'syntax-class-properties',
'transform-decorators-legacy',
{
visitor: {
ImportDeclaration(path) {
imports.push(path.node.source.value)
}
}
}
],
presets: ['react', 'es2015', 'stage-0']
})
return imports
}
const argv = process.argv
if (argv.length !== 3) {
console.log(`
Usage:
node dep.js <path>
for example:
node dep.js ./src/examples
shows every file dependency using import
`)
process.exit(0)
}
const list = []
walker(argv[2], '.js', list)
function showOnlyDependencies() {
const set = {}
list.forEach(path => {
getAllImports(path).forEach(path => {
set[path] = set[path] !== 1 ? 1 : set[path] + 1
})
})
Object.keys(set).forEach(path => {
console.log(`${path} : ${set[path]}`)
})
}
function showPathAndDependencies() {
list.forEach(parentPath => {
console.log(parentPath)
getAllImports(parentPath).forEach(subpath => {
console.log(` ↳ ${trimPath(parentPath, subpath)}`)
})
})
}
function trimPath(parentPath, subPath) {
if (subPath.indexOf('.') === -1) {
return subPath
}
const temp = parentPath.split('/')
if (temp[temp.length - 1].indexOf('.js') !== -1) {
temp.pop()
parentPath = temp.join('/')
}
return path.join(parentPath, subPath)
}
//showOnlyDependencies()
showPathAndDependencies()
// list and merged all dependeies
// list all dependencies
// list.forEach(path => {
// const dependencies = []
// getAllImports(path).forEach(path => {
// dependencies.push(path)
// })
// if (dependencies.length == 0) {
// console.log(path)
// }
// })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment