-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathrequire-chunk-callback-plugin.js
88 lines (69 loc) · 2.19 KB
/
require-chunk-callback-plugin.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
88
const webpack = require( 'webpack' );
const { Template } = webpack;
/**
* Plugin name.
* @type {string}
*/
const PLUGIN_NAME = 'RequireChunkCallback';
class RequireChunkCallbackPlugin {
apply( compiler ) {
compiler.hooks.thisCompilation.tap( PLUGIN_NAME, ( compilation ) => {
const { mainTemplate } = compilation;
const chunkIdToURL = webpack.RuntimeGlobals.getChunkScriptFilename;
mainTemplate.hooks.localVars.tap( PLUGIN_NAME, ( source ) => {
return Template.asString( [
source,
'',
`
// Array to store all loading or loaded chunks
var _installedChunks = [];
function RequireChunkCallback() {
this.callbacks = [];
}
RequireChunkCallback.prototype.add = function( callback ) {
this.callbacks.push( callback );
return this;
};
RequireChunkCallback.prototype.remove = function( callback ) {
this.callbacks = this.callbacks.filter( function( _callback ) {
return callback !== _callback;
} );
return this;
};
RequireChunkCallback.prototype.trigger = function( chunk, promises, publicPath ) {
for ( var i = 0; i < this.callbacks.length; i++ ) {
this.callbacks[ i ]( chunk, promises, publicPath );
}
return this;
};
RequireChunkCallback.prototype.getInstalledChunks = function() {
return _installedChunks.map( function( chunkId ) {
return ${ chunkIdToURL }( chunkId )
.replace( __webpack_require__.p, '' )
.replace( /\\.js$/, '' );
} );
};
RequireChunkCallback.prototype.getPublicPath = function() {
return __webpack_require__.p;
};
var requireChunkCallback = new RequireChunkCallback();
window.__requireChunkCallback__ = requireChunkCallback;
`,
] );
} );
mainTemplate.hooks.requireEnsure.tap( PLUGIN_NAME, ( source ) => {
return Template.asString( [
source,
'',
`requireChunkCallback.trigger( {
chunkId: chunkId,
publicPath: __webpack_require__.p,
scriptSrc: ${ chunkIdToURL }( chunkId )
}, promises );
_installedChunks.push( chunkId );`,
] );
} );
} );
}
}
module.exports = RequireChunkCallbackPlugin;