electron 打包时只会打包 package.json 的 dependencies 中的依赖,而不会自动添加这些依赖所依赖的包,直接导致打包后的应用调用依赖包时出错。例如项目直接依赖于 A,而 A 又依赖于 B,打包时只附带了 A 没有附带 B,这样应用调用 A 时找不到 B 就出错了。
解决方式是将所有依赖的依赖也添加到当前项目的依赖中,所以写一个简单的脚本列举出依赖的依赖:
/** 检查当前依赖包的依赖是否已经添加到依赖列表中 */
import { existsSync, readFileSync, writeFileSync } from 'fs'
import { join } from 'path'
const listNotInstalledDependencies = () => {
const newDependencies = {}
const pkgdata = JSON.parse(readFileSync('package.json', 'utf-8'))
const denpends = pkgdata.dependencies
for (const pkg in denpends) {
const pkgPath = join('node_modules', pkg, 'package.json')
if (!existsSync(pkgPath)) {
console.log(
`[ERROR] ${pkg} is in dependencies of package.json, but not in node_modules, please install it firstly!`
)
return -1
}
const denpends2 = JSON.parse(readFileSync(pkgPath, 'utf-8')).dependencies
for (const k in denpends2) {
if (denpends[k] === undefined) {
newDependencies[k] = denpends2[k]
} else if (denpends[k] !== denpends2[k]) {
console.log(
`[WARNING] Declared version "${denpends[k]}" in package.json, but ${pkg} requires "${denpends2[k]}"`
)
}
}
}
if (Object.keys(newDependencies).length > 0) {
const s = JSON.stringify(newDependencies, null, 2)
console.log(`[INFO] Expected new dependencies:\n${s}`)
pkgdata.dependencies = { ...denpends, ...newDependencies }
console.log(`[INFO] New dependencies have been appended to package.json`)
writeFileSync('package.json', JSON.stringify(pkgdata, null, 2))
} else {
console.log(`[INFO] No new dependencies found!`)
}
}
listNotInstalledDependencies()
评论区