这个函数不理解
class Package {
constructor(options) {
if (!options) {
throw new Error('Package类的参数不能为空')
}
if (!isObject(options)) {
throw new Error('Package类的参数不是一个对象')
}
// 包的路径
this.targetPath = options.targetPath // 包的路径
this.storeDir = options.storeDir // 缓存包的路径
this.packageName = options.packageName // 包的名称
this.packageVersion = options.packageVersion // 包的版本
}
// 判断当前包是否存在
exists() {
if (this.storeDir) { // 这个if什么时候会进来
} else {
return pathExists(this.targetPath)
}
}
// 安装包
install() {
return npminstall({
root: this.targetPath,
storeDir: this.storeDir,
registry: getDefaultRegistry(),
pkgs: [
{ name: this.packageName, version: this.packageVersion }
]
})
}
// 更新Package
update() { }
// 获取入口文件的路径
getRootFilePath() {
// 获取package.json所有目录
const dir = pkgDir(this.targetPath)
if (dir) {
// 读取 package.json
const pkgFile = require(path.resolve(dir, 'package.json'))
if (pkgFile && pkgFile.main) {
return path.resolve(dir, pkgFile.main)
}
}
return null
}
}async function exec(...args) {
// C:\\Users\\xiebenyin\\Desktop\\mk-lg\\xiebenyin-cli-dev\\xiebenyin-cli-dev\\commands\\init
let targetPath = process.env.CLI_TARGET_PATH
let storeDir = '' // 包下载的实际路径
let pkg;
const homePath = process.env.CLI_HOME_PATH
log.verbose('targetPath包的路径', targetPath)
log.verbose('homePath缓存路径', homePath)
const cmdObj = args[args.length - 1]
const cmdName = cmdObj.name() // 命令的名字
const packageName = SETTINGS[cmdName]
const packageVersion = 'latest'
if (!targetPath) {
targetPath = path.resolve(homePath, CACHE_DIR) // 生成缓存路径
storeDir = path.resolve(targetPath, 'node_modules')
log.verbose('targetPath', targetPath)
log.verbose('storeDir', storeDir)
pkg = new Package({
targetPath,
storeDir,
packageName,
packageVersion,
})
if (pkg.exists()) {
// 更新包
} else {
// 下载包
await pkg.install()
}
} else {
pkg = new Package({
targetPath, // 包的路径
packageName, // 包的名称
packageVersion, // 包的版本
})
}
console.log(pkg.exists())
const rootFile = pkg.getRootFilePath()
if (rootFile) {
require(rootFile).apply(null, args)
}
}对函数 exec 里面的 if (pkg.exists())这块不理解
exists 函数在定义的时候判断 storeDir 是否存在来选择执行代码,可是在实例化pkg之前就已经初始化好了storeDir的值,
exists() {
if (this.storeDir) {
} else {
// 这块永远都无法进来
return pathExists(this.targetPath)
}
}22
收起
正在回答 回答被采纳积分+1
1回答
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星