-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
87 lines (76 loc) · 2.29 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
86
87
const EventEmitter = require('events');
const assert = require('assert');
const Primus = require('primus');
const uglify = require('uglify-js');
class PrimusWebpackPlugin {
constructor(options) {
this.options = Object.assign(
{},
{
filename: 'primus-client.js',
minify: false,
primusOptions: {},
},
options
);
}
apply(compiler) {
compiler.plugin('emit', (compilation, cb) => {
const primus = new Primus(new EventEmitter(), this.options.primusOptions);
if (this.options.primusOptions.plugins) {
this.options.primusOptions.plugins.forEach(plugin => {
assert(plugin.name, 'Plugin must have name!');
assert(plugin.plugin, 'Plugin must have plugin!');
primus.plugin(plugin.name, plugin.plugin);
});
}
const clientLib = primus.library();
const filename = this.options.filename.replace(
'[hash]',
compilation.hash
);
const source = this.options.minify
? uglify.minify(clientLib, { fromString: true })
: { code: clientLib };
compilation.assets[filename] = {
source() {
return source.code;
},
size() {
return source.code.length;
},
};
primus.destroy();
cb(null);
});
// if HtmlWebpackPlugin is being utilized, add our script to file
compiler.plugin('compilation', compilation => {
compilation.plugin(
'html-webpack-plugin-before-html-processing',
(htmlPluginData, cb) => {
const filename = this.options.filename.replace(
'[hash]',
compilation.hash
);
const scriptTag = `<script type="text/javascript" src="/${filename}"></script>`;
if (
!htmlPluginData.plugin.options.inject ||
htmlPluginData.plugin.options.inject === 'head'
) {
htmlPluginData.html = htmlPluginData.html.replace(
'</head>',
scriptTag + '</head>'
);
} else {
htmlPluginData.html = htmlPluginData.html.replace(
'</body>',
scriptTag + '</body>'
);
}
cb(null, htmlPluginData);
}
);
});
}
}
module.exports = PrimusWebpackPlugin;