gulpfile.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /**
  2. * FeHelper Chrome Extension Builder By Gulp
  3. * @author zhaoxianlie
  4. */
  5. let gulp = require('gulp');
  6. let clean = require('gulp-clean');
  7. let copy = require('gulp-copy');
  8. let zip = require('gulp-zip');
  9. let uglifyjs = require('gulp-uglify-es').default;
  10. let uglifycss = require('gulp-uglifycss');
  11. let htmlmin = require('gulp-htmlmin');
  12. let jsonmin = require('gulp-jsonminify');
  13. let fs = require('fs');
  14. let through = require('through2');
  15. let path = require('path');
  16. let pretty = require('pretty-bytes');
  17. let shell = require('shelljs');
  18. let babel = require('gulp-babel');
  19. let assert = require('assert');
  20. let gulpIf = require('gulp-if');
  21. let isSilentDetect = false; // <-- 添加全局标志位
  22. // 在Gulp 4.x中,runSequence已被移除,使用gulp.series和gulp.parallel代替
  23. // let runSequence = require('run-sequence');
  24. // 清理输出目录
  25. function cleanOutput() {
  26. return gulp.src('output', {read: false, allowEmpty: true}).pipe(clean({force: true}));
  27. }
  28. // 复制静态资源
  29. function copyAssets() {
  30. return gulp.src(['apps/**/*.{gif,png,jpg,jpeg,cur,ico,ttf,.woff2}', '!apps/static/screenshot/**/*']).pipe(copy('output'));
  31. }
  32. // 处理JSON文件
  33. function processJson() {
  34. return gulp.src('apps/**/*.json').pipe(jsonmin()).pipe(gulp.dest('output/apps'));
  35. }
  36. // 处理HTML文件
  37. function processHtml() {
  38. return gulp.src('apps/**/*.html').pipe(htmlmin({collapseWhitespace: true})).pipe(gulp.dest('output/apps'));
  39. }
  40. // 合并 & 压缩 js
  41. function processJs() {
  42. let jsMerge = () => {
  43. return through.obj(function (file, enc, cb) {
  44. let contents = file.contents.toString('utf-8');
  45. let merge = (fp, fc) => {
  46. // 合并 __importScript
  47. return fc.replace(/__importScript\(\s*(['"])([^'"]*)\1\s*\)/gm, function (frag, $1, mod) {
  48. let mp = path.resolve(fp, '../' + mod + (/\.js$/.test(mod) ? '' : '.js'));
  49. let mc = fs.readFileSync(mp).toString('utf-8');
  50. return merge(mp, mc + ';');
  51. });
  52. };
  53. contents = merge(file.path, contents);
  54. file.contents = Buffer.from(contents);
  55. this.push(file);
  56. return cb();
  57. })
  58. };
  59. // 定义哪些文件不需要 Babel 和 Uglify 处理
  60. const shouldSkipProcessing = (file) => {
  61. const relativePath = path.relative(path.join(process.cwd(), 'apps'), file.path);
  62. // 跳过 chart-maker/lib、static/vendor 和 code-compress 下的文件
  63. return relativePath.startsWith('chart-maker/lib/')
  64. || relativePath.startsWith('static/vendor/')
  65. || relativePath.startsWith('code-compress/');
  66. // 或者更具体地跳过这三个文件:
  67. // return relativePath === 'chart-maker/lib/xlsx.full.min.js'
  68. // || relativePath === 'static/vendor/evalCore.min.js'
  69. // || relativePath === 'code-compress/htmlminifier.min.js';
  70. };
  71. return gulp.src('apps/**/*.js')
  72. .pipe(jsMerge())
  73. .pipe(gulpIf(file => !shouldSkipProcessing(file), babel({
  74. presets: ['@babel/preset-env']
  75. })))
  76. .pipe(gulpIf(file => !shouldSkipProcessing(file), uglifyjs({
  77. compress: {
  78. ecma: 2015
  79. }
  80. })))
  81. .pipe(gulp.dest('output/apps'));
  82. }
  83. // 合并 & 压缩 css
  84. function processCss() {
  85. let cssMerge = () => {
  86. return through.obj(function (file, enc, cb) {
  87. let contents = file.contents.toString('utf-8');
  88. let merge = (fp, fc) => {
  89. return fc.replace(/\@import\s+(url\()?\s*(['"])(.*)\2\s*(\))?\s*;?/gm, function (frag, $1, $2, mod) {
  90. let mp = path.resolve(fp, '../' + mod + (/\.css$/.test(mod) ? '' : '.css'));
  91. let mc = fs.readFileSync(mp).toString('utf-8');
  92. return merge(mp, mc);
  93. });
  94. };
  95. contents = merge(file.path, contents);
  96. file.contents = Buffer.from(contents);
  97. this.push(file);
  98. return cb();
  99. })
  100. };
  101. return gulp.src('apps/**/*.css').pipe(cssMerge()).pipe(uglifycss()).pipe(gulp.dest('output/apps'));
  102. }
  103. // 清理冗余文件,并且打包成zip,发布到chrome webstore
  104. function zipPackage(cb) {
  105. // 读取manifest文件
  106. let pathOfMF = './output/apps/manifest.json';
  107. let manifest = require(pathOfMF);
  108. manifest.name = manifest.name.replace('-Dev', '');
  109. fs.writeFileSync(pathOfMF, JSON.stringify(manifest));
  110. // ============压缩打包================================================
  111. shell.exec('cd output/ && rm -rf fehelper.zip && zip -r fehelper.zip apps/ > /dev/null && cd ../');
  112. let size = fs.statSync('output/fehelper.zip').size;
  113. size = pretty(size);
  114. console.log('\n\n================================================================================');
  115. console.log(' 当前版本:', manifest.version, '\t文件大小:', size);
  116. console.log(' 去Chrome商店发布吧:https://chrome.google.com/webstore/devconsole');
  117. console.log('================================================================================\n\n');
  118. cb();
  119. }
  120. // 打包ms-edge安装包
  121. function edgePackage(cb) {
  122. shell.exec('rm -rf output-edge && cp -r output output-edge && rm -rf output-edge/fehelper.zip');
  123. // 更新edge所需的配置文件
  124. let pathOfMF = './output-edge/apps/manifest.json';
  125. let manifest = require(pathOfMF);
  126. manifest.description = 'FE助手:JSON工具、代码美化、代码压缩、二维码工具、网页定制工具、便签笔记,等等';
  127. delete manifest.update_url;
  128. manifest.version = manifest.version.split('.').map(v => parseInt(v)).join('.');
  129. delete manifest.update_url;
  130. fs.writeFileSync(pathOfMF, JSON.stringify(manifest));
  131. shell.exec('cd output-edge/apps && zip -r ../fehelper.zip ./ > /dev/null && cd ../../');
  132. let size = fs.statSync('output-edge/fehelper.zip').size;
  133. size = pretty(size);
  134. console.log('\n\nfehelper.zip 已打包完成!');
  135. console.log('\n\n================================================================================');
  136. console.log(' 当前版本:', manifest.version, '\t文件大小:', size);
  137. console.log(' 去Edge商店发布吧:https://partner.microsoft.com/zh-cn/dashboard/microsoftedge/overview');
  138. console.log('================================================================================\n\n');
  139. cb();
  140. }
  141. // 打包Firefox安装包
  142. function firefoxPackage(cb) {
  143. shell.exec('rm -rf output-firefox && cp -r output output-firefox && rm -rf output-firefox/fehelper.zip');
  144. // 清理掉firefox里不支持的tools
  145. let rmTools = ['page-capture', 'color-picker', 'ajax-debugger', 'wpo', 'code-standards', 'ruler', 'remove-bg'];
  146. shell.cd('output-firefox/apps');
  147. shell.find('./').forEach(f => {
  148. if (rmTools.includes(f)) {
  149. shell.rm('-rf', f);
  150. console.log('已删除不支持的工具:', f);
  151. }
  152. });
  153. shell.cd('../../');
  154. // 更新firefox所需的配置文件
  155. let pathOfMF = './output-firefox/apps/manifest.json';
  156. let manifest = require(pathOfMF);
  157. manifest.description = 'FE助手:JSON工具、代码美化、代码压缩、二维码工具、网页定制工具、便签笔记,等等';
  158. delete manifest.update_url;
  159. manifest.browser_specific_settings = {
  160. "gecko": {
  161. "id": "[email protected]",
  162. "strict_min_version": "99.0"
  163. }
  164. };
  165. manifest.background = {
  166. "scripts": [
  167. "background/background.js"
  168. ]
  169. };
  170. manifest.version = manifest.version.split('.').map(v => parseInt(v)).join('.');
  171. manifest.content_scripts.splice(1,2);
  172. fs.writeFileSync(pathOfMF, JSON.stringify(manifest));
  173. shell.exec('cd output-firefox/apps && zip -r ../fehelper.xpi ./ > /dev/null && cd ../../');
  174. let size = fs.statSync('output-firefox/fehelper.xpi').size;
  175. size = pretty(size);
  176. console.log('\n\nfehelper.xpi 已打包完成!');
  177. console.log('\n\n================================================================================');
  178. console.log(' 当前版本:', manifest.version, '\t文件大小:', size);
  179. console.log(' 去Chrome商店发布吧:https://addons.mozilla.org/zh-CN/developers/addon/web%E5%89%8D%E7%AB%AF%E5%8A%A9%E6%89%8B-fehelper/versions');
  180. console.log('================================================================================\n\n');
  181. cb();
  182. }
  183. function syncFiles() {
  184. return gulp.src('apps/**/*').pipe(gulp.dest('output/apps'));
  185. }
  186. // 设置静默标志
  187. function setSilentDetect(cb) {
  188. isSilentDetect = true;
  189. cb();
  190. }
  191. // 取消静默标志
  192. function unsetSilentDetect(cb) {
  193. isSilentDetect = false;
  194. cb();
  195. }
  196. // 检测未使用的静态文件
  197. function detectUnusedFiles(cb) {
  198. const allFiles = new Set();
  199. const referencedFiles = new Set();
  200. // 检查文件是否应该被排除
  201. function shouldExcludeFile(filePath) {
  202. // 排除 content-script 文件
  203. if (filePath.includes('content-script.js') || filePath.includes('content-script.css')) {
  204. return true;
  205. }
  206. // 排除 node_modules 目录
  207. if (filePath.includes('node_modules')) {
  208. return true;
  209. }
  210. // 排除 fh-config.js
  211. if (filePath.endsWith('fh-config.js')) {
  212. return true;
  213. }
  214. return false;
  215. }
  216. // 递归获取所有文件
  217. function getAllFiles(dir) {
  218. const files = fs.readdirSync(dir);
  219. files.forEach(file => {
  220. const fullPath = path.join(dir, file);
  221. if (fs.statSync(fullPath).isDirectory()) {
  222. if (file !== 'node_modules') { // 排除 node_modules 目录
  223. getAllFiles(fullPath);
  224. }
  225. } else {
  226. // 只关注静态资源文件,并排除特殊文件
  227. if (/\.(js|css|png|jpg|jpeg|gif|svg)$/i.test(file) && !shouldExcludeFile(fullPath)) {
  228. const relativePath = path.relative('output/apps', fullPath);
  229. allFiles.add(relativePath);
  230. }
  231. }
  232. });
  233. }
  234. // 从文件内容中查找引用
  235. function findReferences(content, filePath) {
  236. const fileDir = path.dirname(filePath);
  237. const patterns = [
  238. // Capture content inside quotes (potential paths)
  239. /['"`][^`'"]*?([./\w-]+\.(?:js|css|png|jpg|jpeg|gif|svg))['"`]/g,
  240. // Capture content inside url()
  241. /url\(['"]?([./\w-]+(?:\.(?:png|jpg|jpeg|gif|svg))?)['"]?\)/gi,
  242. // Capture @import paths
  243. /@import\s+['"]([^'"]+\.css)['"];?/gi,
  244. // Capture src/href attributes, including chrome-extension
  245. /(?:src|href)=['"](chrome-extension:\/\/[^/]+\/)?([^'"?#]+(?:\.(?:js|css|png|jpg|jpeg|gif|svg)))['"]/gi
  246. ];
  247. patterns.forEach((pattern, index) => {
  248. let match;
  249. while ((match = pattern.exec(content)) !== null) {
  250. let extractedPath = '';
  251. // Special handling for src/href pattern which captures optional chrome-extension part
  252. if (index === 3) {
  253. extractedPath = match[2]; // The path part after potential chrome-extension prefix
  254. } else {
  255. extractedPath = match[1];
  256. }
  257. // Skip empty or invalid matches
  258. if (!extractedPath || typeof extractedPath !== 'string') continue;
  259. // Skip special files early
  260. if (shouldExcludeFile(extractedPath)) {
  261. continue;
  262. }
  263. let finalPathToAdd = '';
  264. // Check if it was originally a chrome-extension url (by checking match[1] from the specific regex)
  265. const isChromeExt = index === 3 && match[1];
  266. if (isChromeExt || extractedPath.startsWith('/')) {
  267. // chrome-extension paths are relative to root, absolute paths are relative to root
  268. finalPathToAdd = extractedPath.startsWith('/') ? extractedPath.slice(1) : extractedPath;
  269. } else {
  270. // Resolve relative paths (./, ../, or direct filename)
  271. const absolutePath = path.resolve(fileDir, extractedPath);
  272. finalPathToAdd = path.relative('output/apps', absolutePath);
  273. }
  274. // Final check before adding
  275. if (finalPathToAdd && !shouldExcludeFile(finalPathToAdd)) {
  276. // Ensure consistent path separators (use /) and add to set
  277. referencedFiles.add(finalPathToAdd.replace(/\\/g, '/'));
  278. }
  279. }
  280. });
  281. }
  282. // 读取manifest.json中的引用
  283. function processManifest() {
  284. const manifestPath = 'output/apps/manifest.json';
  285. if (fs.existsSync(manifestPath)) {
  286. const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
  287. // 检查manifest中的各种可能包含资源的字段
  288. const checkManifestField = (obj) => {
  289. if (typeof obj === 'string' && /\.(js|css|png|jpg|jpeg|gif|svg)$/i.test(obj)) {
  290. const normalizedPath = obj.startsWith('/') ? obj.slice(1) : obj;
  291. if (!shouldExcludeFile(normalizedPath)) {
  292. referencedFiles.add(normalizedPath);
  293. }
  294. } else if (Array.isArray(obj)) {
  295. obj.forEach(item => checkManifestField(item));
  296. } else if (typeof obj === 'object' && obj !== null) {
  297. Object.values(obj).forEach(value => checkManifestField(value));
  298. }
  299. };
  300. // 特殊处理content_scripts
  301. if (manifest.content_scripts) {
  302. manifest.content_scripts.forEach(script => {
  303. if (script.js) {
  304. script.js.forEach(js => {
  305. const normalizedPath = js.startsWith('/') ? js.slice(1) : js;
  306. referencedFiles.add(normalizedPath);
  307. });
  308. }
  309. if (script.css) {
  310. script.css.forEach(css => {
  311. const normalizedPath = css.startsWith('/') ? css.slice(1) : css;
  312. referencedFiles.add(normalizedPath);
  313. });
  314. }
  315. });
  316. }
  317. checkManifestField(manifest);
  318. }
  319. }
  320. // 单元测试
  321. function runTests() {
  322. if (!isSilentDetect) console.log('\n运行单元测试...');
  323. // 测试文件排除逻辑
  324. assert.strictEqual(shouldExcludeFile('path/to/content-script.js'), true, 'Should exclude content-script.js');
  325. assert.strictEqual(shouldExcludeFile('path/to/content-script.css'), true, 'Should exclude content-script.css');
  326. assert.strictEqual(shouldExcludeFile('path/to/node_modules/file.js'), true, 'Should exclude node_modules files');
  327. assert.strictEqual(shouldExcludeFile('path/to/normal.js'), false, 'Should not exclude normal files');
  328. // 测试路径解析
  329. const testContent = `
  330. <link rel="stylesheet" href="./style.css">
  331. <script src="../js/script.js"></script>
  332. <img src="/images/test.png">
  333. <div style="background: url('./bg.jpg')">
  334. @import '../common.css';
  335. <img src="chrome-extension://abcdefgh/static/icon.png">
  336. `;
  337. const testFilePath = 'output/apps/test/index.html';
  338. referencedFiles.clear(); // 清理之前的测试数据
  339. findReferences(testContent, testFilePath);
  340. // 验证引用是否被正确解析
  341. const refs = Array.from(referencedFiles);
  342. assert(refs.includes('test/style.css'), 'Should handle relative path with ./');
  343. assert(refs.includes('js/script.js'), 'Should handle relative path with ../');
  344. assert(refs.includes('images/test.png'), 'Should handle absolute path');
  345. assert(refs.includes('test/bg.jpg'), 'Should handle url() in CSS');
  346. assert(refs.includes('common.css'), 'Should handle @import in CSS');
  347. assert(refs.includes('static/icon.png'), 'Should handle chrome-extension urls');
  348. // 清理测试数据
  349. referencedFiles.clear();
  350. if (!isSilentDetect) console.log('单元测试通过!');
  351. }
  352. try {
  353. // 运行单元测试
  354. runTests();
  355. // 执行实际检测
  356. getAllFiles('output/apps');
  357. processManifest();
  358. // 扫描所有文件内容中的引用
  359. const filesToScan = fs.readdirSync('output/apps', { recursive: true })
  360. .filter(file => !shouldExcludeFile(file));
  361. filesToScan.forEach(file => {
  362. const fullPath = path.join('output/apps', file);
  363. if (fs.statSync(fullPath).isFile() && /\.(html|js|css|json)$/i.test(file)) {
  364. const content = fs.readFileSync(fullPath, 'utf8');
  365. findReferences(content, fullPath);
  366. }
  367. });
  368. // 找出未被引用的文件
  369. const unusedFiles = Array.from(allFiles).filter(file => !referencedFiles.has(file));
  370. if (unusedFiles.length > 0) {
  371. if (!isSilentDetect) console.log('\n发现以下未被引用的文件:');
  372. if (!isSilentDetect) console.log('=====================================');
  373. let totalUnusedSize = 0;
  374. unusedFiles.forEach(file => {
  375. if (!isSilentDetect) console.log(file);
  376. try {
  377. const fullPath = path.join('output/apps', file);
  378. if (fs.existsSync(fullPath)) {
  379. totalUnusedSize += fs.statSync(fullPath).size;
  380. // 删除文件
  381. fs.unlinkSync(fullPath);
  382. if (!isSilentDetect) console.log(` -> 已删除: ${file}`);
  383. } else {
  384. if (!isSilentDetect) console.warn(` -> 文件不存在,无法删除或统计大小: ${file}`);
  385. }
  386. } catch (err) {
  387. if (!isSilentDetect) console.warn(`无法删除或获取文件大小: ${file}`, err);
  388. }
  389. });
  390. if (!isSilentDetect) console.log('=====================================');
  391. if (!isSilentDetect) console.log(`共清理 ${unusedFiles.length} 个未使用的文件,释放空间: ${pretty(totalUnusedSize)}`);
  392. // 输出详细信息(仅在DEBUG模式下)
  393. if (process.env.DEBUG && !isSilentDetect) {
  394. console.log('\n调试信息:');
  395. console.log('----------------------------------------');
  396. console.log('所有文件:');
  397. Array.from(allFiles).forEach(file => console.log(`- ${file}`));
  398. console.log('----------------------------------------');
  399. console.log('被引用的文件:');
  400. Array.from(referencedFiles).forEach(file => console.log(`- ${file}`));
  401. }
  402. } else {
  403. if (!isSilentDetect) console.log('\n没有发现未使用的文件!');
  404. }
  405. } catch (error) {
  406. if (!isSilentDetect) console.error('检测过程中发生错误:', error);
  407. }
  408. cb();
  409. }
  410. // 注册任务
  411. gulp.task('clean', cleanOutput);
  412. gulp.task('copy', copyAssets);
  413. gulp.task('json', processJson);
  414. gulp.task('html', processHtml);
  415. gulp.task('js', processJs);
  416. gulp.task('css', processCss);
  417. gulp.task('zip', zipPackage);
  418. gulp.task('edge', edgePackage);
  419. gulp.task('firefox', firefoxPackage);
  420. gulp.task('sync', syncFiles);
  421. gulp.task('detect', detectUnusedFiles);
  422. gulp.task('setSilent', setSilentDetect);
  423. gulp.task('unsetSilent', unsetSilentDetect);
  424. // 定义默认任务 - 在Gulp 4.x中,使用series和parallel代替runSequence
  425. gulp.task('default',
  426. gulp.series(
  427. cleanOutput,
  428. gulp.parallel(copyAssets, processCss, processJs, processHtml, processJson),
  429. setSilentDetect,
  430. detectUnusedFiles,
  431. unsetSilentDetect,
  432. zipPackage
  433. )
  434. );