|
| 1 | +const fs = require('fs'); |
| 2 | +const path = require('path'); |
| 3 | + |
| 4 | +const REACT_HOOKS = [ |
| 5 | + 'useState', |
| 6 | + 'useEffect', |
| 7 | + 'useContext', |
| 8 | + 'useReducer', |
| 9 | + 'useCallback', |
| 10 | + 'useMemo', |
| 11 | + 'useRef', |
| 12 | + 'useImperativeHandle', |
| 13 | + 'useLayoutEffect', |
| 14 | + 'useDebugValue', |
| 15 | + 'useDeferredValue', |
| 16 | + 'useTransition', |
| 17 | + 'useId', |
| 18 | + 'useSyncExternalStore', |
| 19 | + 'useInsertionEffect' |
| 20 | +]; |
| 21 | + |
| 22 | +function checkFile(filePath) { |
| 23 | + const content = fs.readFileSync(filePath, 'utf-8'); |
| 24 | + const errors = []; |
| 25 | + |
| 26 | + for (const hook of REACT_HOOKS) { |
| 27 | + const patterns = [ |
| 28 | + new RegExp(`\\b${hook}\\s*=`), |
| 29 | + new RegExp(`\\bReact\\.${hook}\\b`), |
| 30 | + new RegExp(`import\\s+\\{[^}]*\\b${hook}\\b[^}]*\\}\\s+from\\s+['"]react['"]`), |
| 31 | + new RegExp(`const\\s+\\{\\s*${hook}\\s*\\}\\s*=\\s*React`) |
| 32 | + ]; |
| 33 | + |
| 34 | + for (const pattern of patterns) { |
| 35 | + if (pattern.test(content)) { |
| 36 | + errors.push(`${hook} (${path.basename(filePath)})`); |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + return errors; |
| 42 | +} |
| 43 | + |
| 44 | +function scanDirectory(dir, relativePath = '') { |
| 45 | + let allErrors = []; |
| 46 | + |
| 47 | + if (!fs.existsSync(dir)) { |
| 48 | + return allErrors; |
| 49 | + } |
| 50 | + |
| 51 | + const entries = fs.readdirSync(dir, { withFileTypes: true }); |
| 52 | + |
| 53 | + for (const entry of entries) { |
| 54 | + const fullPath = path.join(dir, entry.name); |
| 55 | + const relPath = path.join(relativePath, entry.name); |
| 56 | + |
| 57 | + if (entry.isDirectory()) { |
| 58 | + if (entry.name === 'node_modules' || entry.name === '.git') { |
| 59 | + continue; |
| 60 | + } |
| 61 | + allErrors = allErrors.concat(scanDirectory(fullPath, relPath)); |
| 62 | + } else if (entry.isFile() && entry.name.endsWith('.js')) { |
| 63 | + allErrors = allErrors.concat(checkFile(fullPath)); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return allErrors; |
| 68 | +} |
| 69 | + |
| 70 | +const skillsDir = path.join(__dirname, '..', 'skills'); |
| 71 | +const errors = scanDirectory(skillsDir); |
| 72 | + |
| 73 | +if (errors.length === 0) { |
| 74 | + console.log('✅ 未检测到 React Hooks 使用'); |
| 75 | + process.exit(0); |
| 76 | +} else { |
| 77 | + console.error('❌ 检测到禁止使用的 React Hooks:'); |
| 78 | + errors.forEach(err => console.error(` - ${err}`)); |
| 79 | + console.error('\n宜搭自定义页面必须使用类组件模式,禁止使用 React Hooks'); |
| 80 | + console.error('请参考 yida-custom-page skill 的开发规范'); |
| 81 | + process.exit(1); |
| 82 | +} |
0 commit comments