-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
64 lines (52 loc) · 2 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
const fs = require('fs');
const path = require('path');
const CDPConnection = require('./src/cdp.js');
const {injectRendererName, injectScript} = require('./src/utils/');
module.exports = function viteNightwatchPlugin(options = {}) {
const enableCdpConnection = options.enableCdpConnection || false;
const renderPage = options.renderPage
? path.resolve(options.renderPage)
: path.resolve(__dirname, 'src', 'renderer.html');
const componentType = options.componentType || 'vue';
return (function () {
let wsUrl;
let cdp;
return {
name: 'nightwatch-plugin',
configResolved(config) {
process.env.BASE_VITE_URL = `http://${config.server.host}:${config.server.port || 5173}`;
},
configureServer(server) {
server.middlewares
// .use(serveStatic(rendererRoot, { index: false }))
.use('/_nightwatch', (req, res, _next) => {
// custom handle request...
const wsUrlParts = decodeURIComponent(req.url).split('?wsurl=');
if (wsUrlParts.length === 2) {
wsUrl = wsUrlParts[1];
}
fs.readFile(renderPage, {encoding: 'utf-8'}, (error, data) => {
if (error) {
throw error;
}
if (wsUrl && enableCdpConnection) {
setTimeout(function () {
cdp = new CDPConnection(wsUrl);
}, 100);
}
const componentPath = new URLSearchParams(req.url.split('?')[1]).get('file');
const htmlWithTitle = injectRendererName(data, componentType);
// Transform HTML using Vite plugins.
server
.transformIndexHtml(
req.url,
componentPath ? injectScript(htmlWithTitle, componentType, componentPath) : htmlWithTitle
)
.then((result) => res.end(result))
.catch((err) => res.end(err.message));
});
});
}
};
})();
};