Skip to content

Instantly share code, notes, and snippets.

@dac09
Last active August 23, 2023 15:05
Show Gist options
  • Save dac09/658e792266b416fad7957dd83b523ee2 to your computer and use it in GitHub Desktop.
Save dac09/658e792266b416fad7957dd83b523ee2 to your computer and use it in GitHub Desktop.
Find all usages of SVG imports in web/src

Usage

If you're in the folder where you want to do a search:

npx https://gist.github.com/dac09/658e792266b416fad7957dd83b523ee2

Or if you want to search a specific directory.

npx https://gist.github.com/dac09/658e792266b416fad7957dd83b523ee2 /path/to/project/to/search
#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const process = require('process')
// Specify the root directory to search
const rootDir = path.join(process.argv[2] || process.cwd(), 'web/src')
function processFile(filePath) {
const fileContent = fs.readFileSync(filePath, 'utf8')
// Find all ".svg" import statements
const importRegex = /import\s+{?\s*(\w+)\s*}?\s+from\s+['"](.+\.svg)['"];?/g
let importMatch
while ((importMatch = importRegex.exec(fileContent)) !== null) {
const importSpecifier = importMatch[1]
// Find usage of default import specifier in React components
const usageRegex = new RegExp(importSpecifier, 'g')
let usageMatch
while ((usageMatch = usageRegex.exec(fileContent)) !== null) {
const lineNumber = getLineNumber(fileContent, usageMatch.index)
const lineContent = getLineContent(fileContent, usageMatch.index)
console.log(`(Line ${lineNumber}): ${lineContent.trim()}`)
}
console.log('~'.repeat(50))
}
}
function getLineNumber(content, index) {
const lines = content.substring(0, index).split('\n')
return lines.length
}
function getLineContent(content, index) {
const start = content.lastIndexOf('\n', index) + 1
const end = content.indexOf('\n', index)
return content.substring(start, end)
}
function traverseDirectory(dirPath) {
const files = fs.readdirSync(dirPath)
files.forEach((file) => {
const filePath = path.join(dirPath, file)
const fileStat = fs.statSync(filePath)
if (fileStat.isDirectory()) {
traverseDirectory(filePath)
} else if (/\.[jt]sx?$/.test(file)) {
processFile(filePath)
}
})
}
traverseDirectory(rootDir)
{
"name": "find-svg-imports-and-usage",
"version": "1.0.3",
"bin": "./findSvgImports.js"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment