-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (64 loc) · 2.21 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
79
80
81
82
83
84
85
const { createServer } = require('http');
const Socket = require('websocket').server;
const createBackgroundWorker = require('./lib/createBackgroundWorker');
const createManifest = require('./lib/createManifest');
const name = 'MyPlugin';
const toAsset = raw => ({
source: () => new Buffer(raw),
size: () => Buffer.byteLength(raw),
});
const defaultOptions = { host: '127.0.0.1', port: 9003 };
class ChromeExtensionPlugin {
constructor(options) {
this.options = { ...defaultOptions, ...options };
this.fileDependencies = [];
}
apply(compiler) {
const { host, port } = this.options;
compiler.hooks.compilation.tap(name, compilation => {
compilation.hooks.additionalAssets.tap(name, () => {
// html-webpack-plugin "fake" compilation fix
if (compilation.entrypoints.get(undefined)) return;
if (compiler.options.mode === 'development') {
compilation.assets['backgroundWorker.js'] = toAsset(
createBackgroundWorker(this.options),
);
}
const [manifest, path] = createManifest(
compilation,
compiler.options.mode,
this.options,
);
if (path) this.fileDependencies.push(path);
compilation.assets['manifest.json'] = toAsset(JSON.stringify(manifest));
});
});
compiler.hooks.afterCompile.tap(name, compilation => {
// html-webpack-plugin "fake" compilation fix
if (compilation.entrypoints.get(undefined)) return;
this.fileDependencies.forEach(path => {
compilation.fileDependencies.add(path);
});
if (this.socket) this.socket.broadcast('RELOAD_EXTENSION');
});
compiler.hooks.watchRun.tap(name, () => {
if (this.socket) return;
this.httpServer = createServer();
this.httpServer.listen({ host, port });
this.socket = new Socket({
httpServer: this.httpServer,
host,
port,
});
this.socket.on('request', request => {
request.accept(null, request.origin);
});
});
compiler.hooks.watchClose.tap(name, () => {
if (!this.socket) return;
this.socket.shutDown();
this.httpServer.close();
});
}
}
module.exports = ChromeExtensionPlugin;