smart-install.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. const fs = require('fs');
  2. const path = require('path');
  3. const { execSync } = require('child_process');
  4. const NODE_MODULES_DIR = 'node_modules';
  5. const PACKAGE_LOCK = 'package-lock.json';
  6. const CACHE_LOCK = path.join(NODE_MODULES_DIR, '.package-lock.json');
  7. const WEBPACK_CACHE_DIR = path.join(NODE_MODULES_DIR, '.cache');
  8. function fileExists(filepath) {
  9. try {
  10. return fs.existsSync(filepath);
  11. } catch (err) {
  12. return false;
  13. }
  14. }
  15. function filesAreEqual(file1, file2) {
  16. try {
  17. const content1 = fs.readFileSync(file1, 'utf8');
  18. const content2 = fs.readFileSync(file2, 'utf8');
  19. return content1 === content2;
  20. } catch (err) {
  21. return false;
  22. }
  23. }
  24. function cleanWebpackCache() {
  25. if (fs.existsSync(WEBPACK_CACHE_DIR)) {
  26. console.log('🧹 检测到依赖变化,清理 Webpack 缓存...');
  27. try {
  28. fs.rmSync(WEBPACK_CACHE_DIR, { recursive: true, force: true });
  29. console.log('✅ Webpack 缓存已清理');
  30. } catch (err) {
  31. console.warn('⚠️ 清理缓存失败(非致命):', err.message);
  32. }
  33. }
  34. }
  35. function runNpmInstall() {
  36. console.log('📦 开始安装依赖...');
  37. try {
  38. // 使用 stdio: 'inherit' 让输出直接显示在控制台
  39. execSync('npm install --force', {
  40. stdio: 'inherit',
  41. encoding: 'utf8'
  42. });
  43. // 安装完成后,保存 package-lock.json 的副本
  44. fs.copyFileSync(PACKAGE_LOCK, CACHE_LOCK);
  45. console.log('✅ 依赖安装完成');
  46. return true;
  47. } catch (error) {
  48. console.error('❌ 安装失败:', error.message);
  49. process.exit(1);
  50. }
  51. }
  52. function main() {
  53. console.log('🔍 检查依赖安装状态...');
  54. console.log(` 平台: ${process.platform} | 架构: ${process.arch} | Node: ${process.version}`);
  55. let needsInstall = false;
  56. // 检查 node_modules 是否存在
  57. if (!fileExists(NODE_MODULES_DIR)) {
  58. console.log('⚠️ node_modules 不存在,需要安装');
  59. needsInstall = true;
  60. }
  61. // 检查缓存的 package-lock.json 是否存在
  62. else if (!fileExists(CACHE_LOCK)) {
  63. console.log('⚠️ 缓存标记不存在,需要安装');
  64. needsInstall = true;
  65. }
  66. // 检查 package-lock.json 是否变化
  67. else if (!filesAreEqual(PACKAGE_LOCK, CACHE_LOCK)) {
  68. console.log('⚠️ package-lock.json 已变化,需要重新安装');
  69. needsInstall = true;
  70. }
  71. else {
  72. console.log('✅ 依赖未变化,跳过安装(节省时间)');
  73. }
  74. if (needsInstall) {
  75. // ✅ 优化:依赖变化时先清理 Webpack 缓存
  76. cleanWebpackCache();
  77. runNpmInstall();
  78. }
  79. }
  80. main();