Skip to content

Commit be0ff0d

Browse files
committed
feat: concat the js files
1 parent 460d7e4 commit be0ff0d

File tree

3 files changed

+72
-4605
lines changed

3 files changed

+72
-4605
lines changed

index.js

+2
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,6 @@ if (isEnabled) {
5050
hexo.extend.filter.register('after_render:js', require('./lib/optimizeJS'));
5151

5252
hexo.extend.filter.register('after_generate', require('./lib/optimizeImage'));
53+
54+
hexo.extend.filter.register('after_generate', require('./lib/concatJS'));
5355
}

lib/concatJS.js

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
'use strict';
2+
3+
const cheerio = require('cheerio');
4+
const Promise = require('bluebird');
5+
6+
function concatJS(data) {
7+
const hexo = this;
8+
const log = hexo.log || console;
9+
const routeList = this.route.list();
10+
11+
log.debug('===============after_generate================');
12+
// 1. get all local scripts
13+
const scripts = [];
14+
const bundlePath = '/js/bundle.js';
15+
return Promise.all(routeList.filter(path => path.endsWith('.html')).map(path => {
16+
return new Promise((resolve, reject) => {
17+
const html = this.route.get(path);
18+
let htmlTxt = ''
19+
html.on('data', (chunk) => (htmlTxt += chunk.trim()));
20+
html.on('end', () => {
21+
const $ = cheerio.load(htmlTxt);
22+
let concat = false;
23+
$('script[src]').each((idx, ele) => {
24+
const $script = $(ele);
25+
const src = $script.attr('src');
26+
// if is local script
27+
if (!src.startsWith('//') && !src.startsWith('http')) {
28+
if (scripts.indexOf(src) === -1) {
29+
scripts.push(src);
30+
}
31+
// remove the script tag from html
32+
log.info('remove script %s from %s', src, path);
33+
$script.remove();
34+
concat = true;
35+
}
36+
});
37+
if (concat) {
38+
log.info('add script %s to %s', bundlePath, path);
39+
$('body').append(`<script type="text/javascript" src="${bundlePath}"></script>`);
40+
this.route.set(path, $.html());
41+
}
42+
log.debug('finish html, a html %s', path);
43+
resolve();
44+
});
45+
});
46+
}))
47+
// 2. concat the script
48+
.then(() => {
49+
log.info('try to concat %s scripts', scripts.length);
50+
return Promise.all(scripts.map(path => {
51+
return new Promise((resolve, reject) => {
52+
const script = this.route.get(path);
53+
log.debug('ready concat script %s', path);
54+
let scriptTxt = '';
55+
script.on('data', chunk => (scriptTxt += chunk.trim()));
56+
script.on('end', () => {
57+
this.route.remove(path);
58+
log.info('concat script %s', path);
59+
resolve(scriptTxt);
60+
});
61+
});
62+
})).then(results => {
63+
const bundleScript = results.reduce((txt, script) => (txt += script), '');
64+
this.route.set(bundlePath, bundleScript);
65+
log.info('finish concat js script');
66+
});
67+
});
68+
}
69+
70+
module.exports = concatJS;

0 commit comments

Comments
 (0)