UNPKG

module-migration-tool

Version:

分析项目文件依赖并迁移到新项目的工具

122 lines (107 loc) 3.24 kB
/** * JavaScript/TypeScript文件分析器 */ const parser = require("@babel/parser") const traverse = require("@babel/traverse").default const fs = require("fs") /** * 分析JS/TS文件的依赖 * @param {string} filePath - 文件路径 * @param {string} content - 文件内容 * @returns {string[]} 依赖路径数组 */ function analyzeJavaScript(filePath, content) { let dependencies = [] try { // 根据文件扩展名确定是否启用TypeScript插件 const isTypeScript = filePath.endsWith(".ts") || filePath.endsWith(".tsx") // 解析代码为AST const ast = parser.parse(content, { sourceType: "module", plugins: [ "jsx", isTypeScript && "typescript", "decorators-legacy", "classProperties", "optionalChaining", "dynamicImport", ].filter(Boolean), }) // 遍历AST查找所有导入 traverse(ast, { // 处理import语句 ImportDeclaration({ node }) { dependencies.push(node.source.value) }, // 处理require()调用 CallExpression({ node }) { if ( node.callee.name === "require" && node.arguments.length > 0 && node.arguments[0].type === "StringLiteral" ) { dependencies.push(node.arguments[0].value) } }, // 处理动态导入 Import({ parent }) { if ( parent.arguments && parent.arguments.length > 0 && parent.arguments[0].type === "StringLiteral" ) { dependencies.push(parent.arguments[0].value) } }, }) return dependencies } catch (error) { console.error(`解析文件 ${filePath} 时出错:`, error.message) // 解析失败时使用正则表达式作为后备方案 return findDependenciesByRegex(content) } } /** * 使用正则表达式查找依赖 * @param {string} content - 文件内容 * @returns {string[]} 依赖路径数组 */ function findDependenciesByRegex(content) { const dependencies = [] // 匹配 import 语句 const importRegex = /import\s+(?:.+\s+from\s+)?['"]([^'"]+)['"]/g let match while ((match = importRegex.exec(content)) !== null) { dependencies.push(match[1]) } // 匹配 require() 调用 const requireRegex = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g while ((match = requireRegex.exec(content)) !== null) { dependencies.push(match[1]) } // 匹配动态导入 const dynamicImportRegex = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g while ((match = dynamicImportRegex.exec(content)) !== null) { dependencies.push(match[1]) } return dependencies } /** * 从文件中分析JS/TS依赖 * @param {string} filePath - 文件路径 * @returns {string[]} 依赖路径数组 */ function analyzeFile(filePath) { try { const content = fs.readFileSync(filePath, "utf-8") return analyzeJavaScript(filePath, content) } catch (error) { console.error(`读取文件 ${filePath} 失败:`, error.message) return [] } } module.exports = { analyzeJavaScript, analyzeFile, findDependenciesByRegex, }