UNPKG

2.48 kBJavaScriptView Raw
1var colors = require("colors");
2var through = require("through2");
3var keys = require("lodash/keys");
4var omit = require("lodash/omit");
5var assign = require("lodash/assign");
6var clone = require("lodash/cloneDeep");
7var defaultTo = require("lodash/defaultTo");
8var isPluginExcludedFromBuild = require("../node/is_plugin_excluded");
9var winston = require("winston");
10
11module.exports = function() {
12 return through.obj(function(data, enc, next) {
13 try {
14 next(null, addAtLoaderShim(data));
15 } catch (err) {
16 next(err);
17 }
18 });
19};
20
21/**
22 * Adds a node to the graph with an "@loader" shim
23 * The "@loader" shim contains the loader configuration properties
24 * @param {Object} data - The slim stream data object
25 * @return {Object} The mutated stream object
26 */
27function addAtLoaderShim(data) {
28 if (includesAtLoader(omit(data.graph, data.loader.configMain))) {
29 winston.warn(
30 colors.yellow(
31 `the @loader module is not fully supported in optimized builds`
32 )
33 );
34
35 var config = clone(
36 omit(data.loader.__loaderConfig, ["paths", "stealPath"])
37 );
38
39 // make sure the "window-production" config overrides previous values
40 assign(config, defaultTo(config.envs, {})["window-production"]);
41
42 data.graph["@loader"] = makeShimNode(data.loader.main, config);
43 }
44
45 return data;
46}
47
48/**
49 * Looks for "@loader" in the dependency graph
50 * @param {Object} graph - The dependency graph
51 * @return {boolean} true if found, false otherwise
52 */
53function includesAtLoader(graph) {
54 var found = false;
55
56 var isAtLoader = function(name) {
57 return name === "@loader";
58 };
59
60 keys(graph).forEach(function(name) {
61 var node = graph[name];
62
63 if (isPluginExcludedFromBuild(node)) {
64 return;
65 }
66
67 if (isAtLoader(name)) {
68 return (found = true);
69 }
70
71 defaultTo(node.dependencies, []).forEach(function(depName) {
72 if (isAtLoader(depName)) {
73 return (found = true);
74 }
75 });
76 });
77
78 return found;
79}
80
81/**
82 * Returns an @loader node with the source code returning the config object
83 * @param {string} main - The main module name
84 * @param {Object} config - The config object exposed by "@loader"
85 * @return {Object} The faux "@loader" graph node
86 */
87function makeShimNode(main, config) {
88 return {
89 bundles: [main],
90 dependencies: [],
91 deps: [],
92 load: {
93 address: "",
94 metadata: {
95 deps: [],
96 format: "amd",
97 dependencies: []
98 },
99 name: "@loader",
100 source: `
101 define("@loader", function() {
102 return ${JSON.stringify(config)};
103 });
104 `
105 }
106 };
107}