gulpfile.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. const FIREFOX_REMOVE_TOOLS = [
  27. 'color-picker', 'postman', 'devtools', 'websocket', 'page-timing',
  28. 'grid-ruler', 'naotu', 'screenshot', 'page-monkey', 'excel2json'
  29. ];
  30. // 清理输出目录
  31. function cleanOutput(outputDir = 'output-chrome') {
  32. return gulp.src(outputDir, {read: false, allowEmpty: true}).pipe(clean({force: true}));
  33. }
  34. // 复制静态资源
  35. function copyAssets(outputDir = 'output-chrome/apps') {
  36. return gulp.src(['apps/**/*.{gif,png,jpg,jpeg,cur,ico,ttf,woff2,svg,md,txt,json}']).pipe(gulp.dest(outputDir));
  37. }
  38. // 处理JSON文件
  39. function processJson(outputDir = 'output-chrome/apps') {
  40. return gulp.src('apps/**/*.json').pipe(jsonmin()).pipe(gulp.dest(outputDir));
  41. }
  42. // 处理HTML文件
  43. function processHtml(outputDir = 'output-chrome/apps') {
  44. return gulp.src('apps/**/*.html').pipe(htmlmin({collapseWhitespace: true})).pipe(gulp.dest(outputDir));
  45. }
  46. // 合并 & 压缩 js
  47. function processJs(outputDir = 'output-chrome/apps') {
  48. let jsMerge = () => {
  49. return through.obj(function (file, enc, cb) {
  50. let contents = file.contents.toString('utf-8');
  51. let merge = (fp, fc) => {
  52. return fc.replace(/__importScript\(\s*(['"])([^'"]*)\1\s*\)/gm, function (frag, $1, mod) {
  53. let mp = path.resolve(fp, '../' + mod + (/\.js$/.test(mod) ? '' : '.js'));
  54. let mc = fs.readFileSync(mp).toString('utf-8');
  55. return merge(mp, mc + ';');
  56. });
  57. };
  58. contents = merge(file.path, contents);
  59. file.contents = Buffer.from(contents);
  60. this.push(file);
  61. return cb();
  62. })
  63. };
  64. const shouldSkipProcessing = (file) => {
  65. const relativePath = path.relative(path.join(process.cwd(), 'apps'), file.path);
  66. return relativePath === 'chart-maker/lib/xlsx.full.min.js'
  67. || relativePath === 'static/vendor/evalCore.min.js'
  68. || relativePath === 'code-compress/htmlminifier.min.js';
  69. };
  70. return gulp.src('apps/**/*.js')
  71. .pipe(jsMerge())
  72. .pipe(gulpIf(file => !shouldSkipProcessing(file), babel({
  73. presets: [
  74. ['@babel/preset-env', { modules: false }]
  75. ]
  76. })))
  77. .pipe(gulpIf(file => !shouldSkipProcessing(file), uglifyjs({
  78. compress: {
  79. ecma: 2015
  80. }
  81. })))
  82. .pipe(gulp.dest(outputDir));
  83. }
  84. // 合并 & 压缩 css
  85. function processCss(outputDir = 'output-chrome/apps') {
  86. let cssMerge = () => {
  87. return through.obj(function (file, enc, cb) {
  88. let contents = file.contents.toString('utf-8');
  89. let merge = (fp, fc) => {
  90. return fc.replace(/\@import\s+(url\()?\s*(['"])(.*)\2\s*(\))?\s*;?/gm, function (frag, $1, $2, mod) {
  91. let mp = path.resolve(fp, '../' + mod + (/\.css$/.test(mod) ? '' : '.css'));
  92. let mc = fs.readFileSync(mp).toString('utf-8');
  93. return merge(mp, mc);
  94. });
  95. };
  96. contents = merge(file.path, contents);
  97. file.contents = Buffer.from(contents);
  98. this.push(file);
  99. return cb();
  100. })
  101. };
  102. return gulp.src('apps/**/*.css').pipe(cssMerge()).pipe(uglifycss()).pipe(gulp.dest(outputDir));
  103. }
  104. // 添加图片压缩任务
  105. function compressImages(outputDir = 'output-chrome/apps') {
  106. return gulp.src(path.join(outputDir, '**/*.{png,jpg,jpeg,gif,svg}'))
  107. .pipe(imagemin([
  108. imageminGifsicle({interlaced: true}),
  109. imageminMozjpeg({quality: 75, progressive: true}),
  110. imageminSvgo({
  111. plugins: [
  112. {removeViewBox: true},
  113. {cleanupIDs: false}
  114. ]
  115. })
  116. ]))
  117. .pipe(gulp.dest(outputDir));
  118. }
  119. // 清理冗余文件,并且打包成zip,发布到chrome webstore
  120. function zipPackage(outputRoot = 'output-chrome', cb) {
  121. let pathOfMF = path.join(outputRoot, 'apps/manifest.json');
  122. let manifest = require(path.resolve(pathOfMF));
  123. manifest.name = manifest.name.replace('-Dev', '');
  124. fs.writeFileSync(pathOfMF, JSON.stringify(manifest));
  125. let pkgName = 'fehelper.zip';
  126. if (outputRoot === 'output-firefox') {
  127. pkgName = 'fehelper.xpi';
  128. }
  129. shell.exec(`cd ${outputRoot}/apps && rm -rf ../${pkgName} && zip -r ../${pkgName} ./* > /dev/null && cd ../../`);
  130. let size = fs.statSync(`${outputRoot}/${pkgName}`).size;
  131. size = pretty(size);
  132. console.log('\n\n================================================================================');
  133. console.log(' 当前版本:', manifest.version, '\t文件大小:', size);
  134. if (outputRoot === 'output-chrome') {
  135. console.log(' 去Chrome商店发布吧:https://chrome.google.com/webstore/devconsole');
  136. } else if (outputRoot === 'output-edge') {
  137. console.log(' 去Edge商店发布吧:https://partner.microsoft.com/zh-cn/dashboard/microsoftedge/overview');
  138. } else if (outputRoot === 'output-firefox') {
  139. console.log(' 去Firefox商店发布吧:https://addons.mozilla.org/zh-CN/developers/addon/web前端助手-fehelper/versions');
  140. }
  141. console.log('================================================================================\n\n');
  142. if (cb) cb();
  143. }
  144. // 设置静默标志
  145. function setSilentDetect(cb) {
  146. isSilentDetect = true;
  147. cb();
  148. }
  149. function unsetSilentDetect(cb) {
  150. isSilentDetect = false;
  151. cb();
  152. }
  153. // 检测未使用的静态文件(参数化outputDir)
  154. function detectUnusedFiles(outputDir = 'output-chrome/apps', cb) {
  155. const allFiles = new Set();
  156. const referencedFiles = new Set();
  157. function shouldExcludeFile(filePath) {
  158. if (filePath.includes('content-script.js') || filePath.includes('content-script.css')) return true;
  159. if (filePath.includes('node_modules')) return true;
  160. if (filePath.endsWith('fh-config.js')) return true;
  161. return false;
  162. }
  163. function getAllFiles(dir) {
  164. const files = fs.readdirSync(dir);
  165. files.forEach(file => {
  166. const fullPath = path.join(dir, file);
  167. if (fs.statSync(fullPath).isDirectory()) {
  168. if (file !== 'node_modules') {
  169. getAllFiles(fullPath);
  170. }
  171. } else {
  172. if (/\.(js|css|png|jpg|jpeg|gif|svg)$/i.test(file) && !shouldExcludeFile(fullPath)) {
  173. const relativePath = path.relative(outputDir, fullPath);
  174. allFiles.add(relativePath);
  175. }
  176. }
  177. });
  178. }
  179. function findReferences(content, filePath) {
  180. const fileDir = path.dirname(filePath);
  181. const patterns = [
  182. /['"`][^`'\"]*?([./\w-]+\.(?:js|css|png|jpg|jpeg|gif|svg))['"`]/g,
  183. /url\(['"]?([./\w-]+(?:\.(?:png|jpg|jpeg|gif|svg))?)['"]?\)/gi,
  184. /@import\s+['"]([^'\"]+\.css)['"];?/gi,
  185. /(?:src|href)=['"](chrome-extension:\/\/[^/]+\/)?([^'"?#]+(?:\.(?:js|css|png|jpg|jpeg|gif|svg)))['"]/gi
  186. ];
  187. patterns.forEach((pattern, index) => {
  188. let match;
  189. while ((match = pattern.exec(content)) !== null) {
  190. let extractedPath = '';
  191. if (index === 3) {
  192. extractedPath = match[2];
  193. } else {
  194. extractedPath = match[1];
  195. }
  196. if (!extractedPath || typeof extractedPath !== 'string') continue;
  197. if (shouldExcludeFile(extractedPath)) continue;
  198. let finalPathToAdd = '';
  199. const isChromeExt = index === 3 && match[1];
  200. if (isChromeExt || extractedPath.startsWith('/')) {
  201. finalPathToAdd = extractedPath.startsWith('/') ? extractedPath.slice(1) : extractedPath;
  202. } else {
  203. const absolutePath = path.resolve(fileDir, extractedPath);
  204. finalPathToAdd = path.relative(outputDir, absolutePath);
  205. }
  206. if (finalPathToAdd && !shouldExcludeFile(finalPathToAdd)) {
  207. referencedFiles.add(finalPathToAdd.replace(/\\/g, '/'));
  208. }
  209. }
  210. });
  211. }
  212. function processManifest() {
  213. const manifestPath = path.join(outputDir, 'manifest.json');
  214. if (fs.existsSync(manifestPath)) {
  215. const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
  216. const checkManifestField = (obj) => {
  217. if (typeof obj === 'string' && /\.(js|css|png|jpg|jpeg|gif|svg)$/i.test(obj)) {
  218. const normalizedPath = obj.startsWith('/') ? obj.slice(1) : obj;
  219. if (!shouldExcludeFile(normalizedPath)) {
  220. referencedFiles.add(normalizedPath);
  221. }
  222. } else if (Array.isArray(obj)) {
  223. obj.forEach(item => checkManifestField(item));
  224. } else if (typeof obj === 'object' && obj !== null) {
  225. Object.values(obj).forEach(value => checkManifestField(value));
  226. }
  227. };
  228. if (manifest.content_scripts) {
  229. manifest.content_scripts.forEach(script => {
  230. if (script.js) {
  231. script.js.forEach(js => {
  232. const normalizedPath = js.startsWith('/') ? js.slice(1) : js;
  233. referencedFiles.add(normalizedPath);
  234. });
  235. }
  236. if (script.css) {
  237. script.css.forEach(css => {
  238. const normalizedPath = css.startsWith('/') ? css.slice(1) : css;
  239. referencedFiles.add(normalizedPath);
  240. });
  241. }
  242. });
  243. }
  244. checkManifestField(manifest);
  245. }
  246. }
  247. function runTests() {
  248. if (!isSilentDetect) console.log('\n运行单元测试...');
  249. assert.strictEqual(shouldExcludeFile('path/to/content-script.js'), true, 'Should exclude content-script.js');
  250. assert.strictEqual(shouldExcludeFile('path/to/content-script.css'), true, 'Should exclude content-script.css');
  251. assert.strictEqual(shouldExcludeFile('path/to/node_modules/file.js'), true, 'Should exclude node_modules files');
  252. assert.strictEqual(shouldExcludeFile('path/to/normal.js'), false, 'Should not exclude normal files');
  253. const testContent = `
  254. <link rel="stylesheet" href="./style.css">
  255. <script src="../js/script.js"></script>
  256. <img src="/images/test.png">
  257. <div style="background: url('./bg.jpg')">
  258. @import '../common.css';
  259. <img src="chrome-extension://abcdefgh/static/icon.png">
  260. `;
  261. const testFilePath = path.join(outputDir, 'test/index.html');
  262. referencedFiles.clear();
  263. findReferences(testContent, testFilePath);
  264. const refs = Array.from(referencedFiles);
  265. assert(refs.includes('test/style.css'), 'Should handle relative path with ./');
  266. assert(refs.includes('js/script.js'), 'Should handle relative path with ../');
  267. assert(refs.includes('images/test.png'), 'Should handle absolute path');
  268. assert(refs.includes('test/bg.jpg'), 'Should handle url() in CSS');
  269. assert(refs.includes('common.css'), 'Should handle @import in CSS');
  270. assert(refs.includes('static/icon.png'), 'Should handle chrome-extension urls');
  271. referencedFiles.clear();
  272. if (!isSilentDetect) console.log('单元测试通过!');
  273. }
  274. try {
  275. runTests();
  276. getAllFiles(outputDir);
  277. processManifest();
  278. const filesToScan = fs.readdirSync(outputDir, { recursive: true })
  279. .filter(file => !shouldExcludeFile(file));
  280. filesToScan.forEach(file => {
  281. const fullPath = path.join(outputDir, file);
  282. if (fs.statSync(fullPath).isFile() && /\.(html|js|css|json)$/i.test(file)) {
  283. const content = fs.readFileSync(fullPath, 'utf8');
  284. findReferences(content, fullPath);
  285. }
  286. });
  287. const unusedFiles = Array.from(allFiles).filter(file => !referencedFiles.has(file));
  288. if (unusedFiles.length > 0) {
  289. if (!isSilentDetect) console.log('\n发现以下未被引用的文件:');
  290. if (!isSilentDetect) console.log('=====================================');
  291. let totalUnusedSize = 0;
  292. unusedFiles.forEach(file => {
  293. if (!isSilentDetect) console.log(file);
  294. try {
  295. const fullPath = path.join(outputDir, file);
  296. if (fs.existsSync(fullPath)) {
  297. totalUnusedSize += fs.statSync(fullPath).size;
  298. fs.unlinkSync(fullPath);
  299. if (!isSilentDetect) console.log(` -> 已删除: ${file}`);
  300. } else {
  301. if (!isSilentDetect) console.warn(` -> 文件不存在,无法删除或统计大小: ${file}`);
  302. }
  303. } catch (err) {
  304. if (!isSilentDetect) console.warn(`无法删除或获取文件大小: ${file}`, err);
  305. }
  306. });
  307. if (!isSilentDetect) console.log('=====================================');
  308. if (!isSilentDetect) console.log(`共清理 ${unusedFiles.length} 个未使用的文件,释放空间: ${pretty(totalUnusedSize)}`);
  309. if (process.env.DEBUG && !isSilentDetect) {
  310. console.log('\n调试信息:');
  311. console.log('----------------------------------------');
  312. console.log('所有文件:');
  313. Array.from(allFiles).forEach(file => console.log(`- ${file}`));
  314. console.log('----------------------------------------');
  315. console.log('被引用的文件:');
  316. Array.from(referencedFiles).forEach(file => console.log(`- ${file}`));
  317. }
  318. } else {
  319. if (!isSilentDetect) console.log('\n没有发现未使用的文件!');
  320. }
  321. } catch (error) {
  322. if (!isSilentDetect) console.error('检测过程中发生错误:', error);
  323. }
  324. cb && cb();
  325. }
  326. // Firefox前置处理
  327. function firefoxPreprocess(cb) {
  328. const srcDir = 'apps';
  329. const destDir = 'output-firefox/apps';
  330. shell.exec(`mv ${destDir}/firefox.json ${destDir}/manifest.json`);
  331. shell.exec(`rm -rf ${destDir}/chrome.json`);
  332. shell.exec(`rm -rf ${destDir}/edge.json`);
  333. FIREFOX_REMOVE_TOOLS.forEach(tool => {
  334. const toolDir = path.join(destDir, tool);
  335. if (fs.existsSync(toolDir)) {
  336. shell.exec(`rm -rf ${toolDir}`);
  337. }
  338. });
  339. cb();
  340. }
  341. // chrome前置处理
  342. function chromePreprocess(cb) {
  343. const destDir = 'output-chrome/apps';
  344. shell.exec(`mv ${destDir}/chrome.json ${destDir}/manifest.json`);
  345. shell.exec(`rm -rf ${destDir}/firefox.json`);
  346. shell.exec(`rm -rf ${destDir}/edge.json`);
  347. cb();
  348. }
  349. // edge前置处理
  350. function edgePreprocess(cb) {
  351. const destDir = 'output-edge/apps';
  352. shell.exec(`mv ${destDir}/edge.json ${destDir}/manifest.json`);
  353. shell.exec(`rm -rf ${destDir}/chrome.json`);
  354. shell.exec(`rm -rf ${destDir}/firefox.json`);
  355. cb();
  356. }
  357. // 注册任务
  358. // Chrome默认打包
  359. function cleanChrome() { return cleanOutput('output-chrome'); }
  360. function copyChrome() { return copyAssets('output-chrome/apps'); }
  361. function cssChrome() { return processCss('output-chrome/apps'); }
  362. function jsChrome() { return processJs('output-chrome/apps'); }
  363. function htmlChrome() { return processHtml('output-chrome/apps'); }
  364. function jsonChrome() { return processJson('output-chrome/apps'); }
  365. function detectChrome(cb) { detectUnusedFiles('output-chrome/apps', cb); }
  366. function zipChrome(cb) { zipPackage('output-chrome', cb); }
  367. gulp.task('default',
  368. gulp.series(
  369. cleanChrome,
  370. copyChrome,
  371. gulp.parallel(cssChrome, jsChrome, htmlChrome, jsonChrome),
  372. chromePreprocess,
  373. setSilentDetect,
  374. detectChrome,
  375. unsetSilentDetect,
  376. zipChrome
  377. )
  378. );
  379. // ------------------------------------------------------------
  380. // edge打包
  381. function cleanEdge() { return cleanOutput('output-edge'); }
  382. function copyEdge() { return copyAssets('output-edge/apps'); }
  383. function cssEdge() { return processCss('output-edge/apps'); }
  384. function jsEdge() { return processJs('output-edge/apps'); }
  385. function htmlEdge() { return processHtml('output-edge/apps'); }
  386. function jsonEdge() { return processJson('output-edge/apps'); }
  387. function detectEdge(cb) { detectUnusedFiles('output-edge/apps', cb); }
  388. function zipEdge(cb) { zipPackage('output-edge', cb); }
  389. gulp.task('edge',
  390. gulp.series(
  391. cleanEdge,
  392. copyEdge,
  393. gulp.parallel(cssEdge, jsEdge, htmlEdge, jsonEdge),
  394. edgePreprocess,
  395. setSilentDetect,
  396. detectEdge,
  397. unsetSilentDetect,
  398. zipEdge
  399. )
  400. );
  401. // Firefox打包主任务
  402. function cleanFirefox() { return cleanOutput('output-firefox'); }
  403. function copyFirefox() { return copyAssets('output-firefox/apps'); }
  404. function cssFirefox() { return processCss('output-firefox/apps'); }
  405. function jsFirefox() { return processJs('output-firefox/apps'); }
  406. function htmlFirefox() { return processHtml('output-firefox/apps'); }
  407. function jsonFirefox() { return processJson('output-firefox/apps'); }
  408. function detectFirefox(cb) { detectUnusedFiles('output-firefox/apps', cb); }
  409. function zipFirefox(cb) { zipPackage('output-firefox', cb); }
  410. gulp.task('firefox',
  411. gulp.series(
  412. cleanFirefox,
  413. copyFirefox,
  414. gulp.parallel(cssFirefox, jsFirefox, htmlFirefox, jsonFirefox),
  415. firefoxPreprocess,
  416. setSilentDetect,
  417. detectFirefox,
  418. unsetSilentDetect,
  419. zipFirefox
  420. )
  421. );