-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (62 loc) · 1.94 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* Copyright (c) 2023 Anthony Mugendi
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
const fs = require('fs');
const path = require('path');
const reloadSite = require('reloadsite');
const tcpPortUsed = require('tcp-port-used');
const picomatch = require('picomatch');
let scriptJSStr = fs.readFileSync(
path.join(__dirname, './src/plugin-append-script.js'),
'utf8'
);
const production = !process.env.ROLLUP_WATCH;
const ReloadSite = (options = {}) => {
let { dirs = [], port = 35729, delay = 1000, filter = null } = options;
// console.log(options);
return {
name: 'reloadsite-plugin',
async generateBundle(options, bundle, isWrite) {
// start server
try {
// do not run in production
if (production) return;
// add watcher script to js code
for (let id in bundle) {
// use picomatch to filter files
let fileMatchesFilter = !filter
? true
: picomatch.isMatch(id, filter);
if (!fileMatchesFilter) continue;
if (/.+\.[cm]?js$/.test(id)) {
// Add script
scriptJSStr = scriptJSStr.replace('{PORT}', port);
bundle[id].code += '\n\n' + scriptJSStr;
scriptJSAdded = true;
}
}
// start server
const portUsed = await tcpPortUsed.check(port, '127.0.0.1');
// by using portUsed, we ensure we start server only once
if (!portUsed) {
startReloadSiteServer({ port, dirs, delay });
}
} catch (error) {
console.error(error);
throw error;
}
},
};
};
async function startReloadSiteServer({ port, delay = 1000, dirs = [] }) {
// start server
const serverOptions = { port };
const reloader = reloadSite(serverOptions);
// start watching directories
let reloadOptions = { delay };
reloader.watch(dirs, reloadOptions);
}
module.exports = ReloadSite;