module-migration-tool
Version:
分析项目文件依赖并迁移到新项目的工具
131 lines (116 loc) • 3.47 kB
JavaScript
/**
* 路径解析模块
*/
const fs = require("fs")
const path = require("path")
const { resolveAliasPath } = require("./aliasResolver")
/**
* 解析依赖路径
* @param {string} importPath - 导入路径
* @param {string} currentFilePath - 当前文件路径
* @param {Object} config - 配置
* @param {string} sourcePath - 源目录路径
* @returns {string|null} 解析后的绝对路径,如果无法解析则返回null
*/
function resolveDependencyPath(
importPath,
currentFilePath,
config,
sourcePath
) {
// 过滤掉标准库导入
if (isNodeModulePath(importPath)) {
return null
}
// 解析别名路径
if (isAliasPath(importPath)) {
const resolvedPath = resolveAliasPath(importPath, config.alias, sourcePath)
if (resolvedPath) {
return resolveWithExtension(resolvedPath, config.extensions)
}
}
// 处理相对路径
if (isRelativePath(importPath)) {
const absolutePath = path.resolve(path.dirname(currentFilePath), importPath)
return resolveWithExtension(absolutePath, config.extensions)
}
// 处理绝对路径(从项目根目录开始的路径)
if (isAbsolutePath(importPath)) {
const absolutePath = path.resolve(sourcePath, importPath.substring(1))
return resolveWithExtension(absolutePath, config.extensions)
}
// 无法解析的路径
return null
}
/**
* 添加扩展名并检查文件是否存在
* @param {string} filePath - 文件路径
* @param {Array<string>} extensions - 扩展名数组
* @returns {string|null} 解析后的路径
*/
function resolveWithExtension(filePath, extensions) {
// 如果路径已有扩展名且文件存在,直接返回
if (path.extname(filePath) && fs.existsSync(filePath)) {
return filePath
}
// 尝试添加扩展名
for (const ext of extensions) {
const pathWithExt = `${filePath}${ext}`
if (fs.existsSync(pathWithExt)) {
return pathWithExt
}
}
// 尝试作为目录的index文件
for (const ext of extensions) {
const indexPath = path.join(filePath, `index${ext}`)
if (fs.existsSync(indexPath)) {
return indexPath
}
}
// 无法解析
return null
}
/**
* 判断是否为node_modules路径
* @param {string} importPath - 导入路径
* @returns {boolean} 是否为node_modules路径
*/
function isNodeModulePath(importPath) {
// 不以./, ../, /, @开头的路径,通常是指node_modules中的模块
return !(
importPath.startsWith(".") ||
importPath.startsWith("/") ||
importPath.startsWith("@")
)
}
/**
* 判断是否为相对路径
* @param {string} importPath - 导入路径
* @returns {boolean} 是否为相对路径
*/
function isRelativePath(importPath) {
return importPath.startsWith("./") || importPath.startsWith("../")
}
/**
* 判断是否为别名路径
* @param {string} importPath - 导入路径
* @returns {boolean} 是否为别名路径
*/
function isAliasPath(importPath) {
return importPath.startsWith("@") || importPath.startsWith("~")
}
/**
* 判断是否为绝对路径
* @param {string} importPath - 导入路径
* @returns {boolean} 是否为绝对路径
*/
function isAbsolutePath(importPath) {
return importPath.startsWith("/")
}
module.exports = {
resolveDependencyPath,
isNodeModulePath,
isRelativePath,
isAliasPath,
isAbsolutePath,
}