gulpfile.js 21 KB

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