Skip to content

Instantly share code, notes, and snippets.

@f3r
Last active October 11, 2023 11:26
Show Gist options
  • Save f3r/3f8d7569ed084c0078e705af25bf7a95 to your computer and use it in GitHub Desktop.
Save f3r/3f8d7569ed084c0078e705af25bf7a95 to your computer and use it in GitHub Desktop.
Counting imports in vue3 project
/* eslint-disable no-undef */
/*
Instructions:
1. Place this script in the root directory of your Vue.js project.
2. Run `node count_imports.js` to count the occurrences of each imported file in `.vue` files within the `src` directory.
3. Add the optional command-line argument `--show-files` if you also want to see the file references for each import.
For example, run `node count_imports.js --show-files`.
Output Example:
Without --show-files:
03 - @/layouts/OrgNav.vue
01 - @/layouts/OrgNav.2vue
With --show-files:
03 - @/layouts/OrgNav.vue
--> /views/PageOne.vue
--> /views/PageTwo.vue
01 - @/layouts/OrgNav.2vue
--> /views/PageThree.vue
*/
const fs = require('fs')
const path = require('path')
const showFiles = process.argv.includes('--show-files')
const importPaths = []
const fileReferences = {}
function processFiles(directory) {
const files = fs.readdirSync(directory)
files.forEach(file => {
const filePath = path.join(directory, file)
const stat = fs.statSync(filePath)
if (stat.isDirectory()) {
processFiles(filePath)
} else if (stat.isFile() && path.extname(filePath) === '.vue') {
const fileContent = fs.readFileSync(filePath, 'utf-8')
const lines = fileContent.split('\n')
const relativeFilePath = filePath.replace(/^\.\/src\//, '')
lines.forEach(line => {
const match = line.match(/^import .+ from '(.+)'/)
if (match) {
const importPath = match[1]
importPaths.push(importPath)
if (!fileReferences[importPath]) {
fileReferences[importPath] = []
}
fileReferences[importPath].push(relativeFilePath)
}
})
}
})
}
function countImports(importPaths) {
return importPaths.reduce((acc, importPath) => {
acc[importPath] = (acc[importPath] || 0) + 1
return acc
}, {})
}
const directoryPath = './src'
processFiles(directoryPath)
const importCounts = countImports(importPaths)
const sortedImportPaths = Object.keys(importCounts).sort((a, b) => importCounts[b] - importCounts[a])
sortedImportPaths.forEach(importPath => {
if (showFiles) {
console.log(`\n${importCounts[importPath].toString().padStart(2, '0')} - ${importPath}`)
} else {
console.log(`${importCounts[importPath].toString().padStart(2, '0')} - ${importPath}`)
}
if (showFiles && fileReferences[importPath]) {
fileReferences[importPath].forEach(reference => {
console.log(` --> ${reference}`)
})
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment