-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathRequireJsLoaderPlugin.js
59 lines (48 loc) · 1.91 KB
/
RequireJsLoaderPlugin.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
'use strict';
const ConcatSource = require('webpack-sources').ConcatSource;
let RequireJsLoaderPlugin = function () {
};
function gatherRequireJsImports(modules) {
let needsImport = [];
for (let module of modules) {
// If the requirejs-loader was used, then we need to wrap and import this module.
// It's safe to use mixins! in all cases, and necessary for anything where require('mixins').hasMixins(module) is true.
// TODO: Clean up this check.
if (module.request && module.request.indexOf('requirejs-loader') !== -1) {
needsImport.push('mixins!' + module.rawRequest);
}
}
return needsImport;
}
function generateProlog(imports) {
const jsonImports = JSON.stringify(imports);
return `window.require(${jsonImports}, function () {`;
}
function generateEpilog(imports) {
return `});`;
}
function registerHook(object, oldName, newName, cb) {
if (object.hooks) {
object.hooks[newName].tap('RequireJsLoader', cb);
} else {
object.plugin(oldName, cb);
}
}
RequireJsLoaderPlugin.prototype.apply = function (compiler) {
registerHook(compiler, 'compilation', 'compilation', (compilation, data) => {
registerHook(compilation, 'chunk-asset', 'chunkAsset', (chunk, filename) => {
// Avoid applying imports twice.
if ('--requirejs-export:done' in chunk) {
return;
}
const modules = chunk.modulesIterable ? Array.from(chunk.modulesIterable) : modules;
const needsImport = gatherRequireJsImports(modules);
if (needsImport.length != 0) {
let prolog = generateProlog(needsImport);
let epilog = generateEpilog(needsImport);
compilation.assets[filename] = new ConcatSource(prolog, "\n", compilation.assets[filename], "\n", epilog);
}
});
});
};
module.exports = RequireJsLoaderPlugin;