gulpfile.js 21 KB

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