From a84db65990cc064e407c9496914002c6b6048512 Mon Sep 17 00:00:00 2001 From: Christian Tellnes Date: Mon, 7 Dec 2015 03:06:38 +0100 Subject: [PATCH] Expose `require` before initializing entries --- index.js | 15 ++++++++++----- prelude.js | 12 ++++++++---- test/external.js | 43 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 9 deletions(-) create mode 100644 test/external.js diff --git a/index.js b/index.js index 9d3ab70..6425351 100644 --- a/index.js +++ b/index.js @@ -46,10 +46,6 @@ module.exports = function (opts) { var pre = umd.prelude(opts.standalone).trim(); stream.push(Buffer(pre + 'return ')); } - else if (first && stream.hasExports) { - var pre = opts.externalRequireName || 'require'; - stream.push(Buffer(pre + '=')); - } if (first) stream.push(Buffer(prelude + '({')); if (row.sourceFile && !row.nomap) { @@ -96,7 +92,16 @@ module.exports = function (opts) { if (first) stream.push(Buffer(prelude + '({')); entries = entries.filter(function (x) { return x !== undefined }); - stream.push(Buffer('},{},' + JSON.stringify(entries) + ')')); + var postlude = [ + '}', + '{}', + JSON.stringify(entries), + 'this', // this === window + stream.hasExports ? 'true' : 'false', + JSON.stringify(opts.externalRequireName || 'require') + ].join(','); + + stream.push(Buffer(postlude + ')')); if (opts.standalone && !first) { stream.push(Buffer( diff --git a/prelude.js b/prelude.js index d291c69..b54239f 100644 --- a/prelude.js +++ b/prelude.js @@ -7,9 +7,9 @@ // anything defined in a previous bundle is accessed via the // orig method which is the requireuire for previous bundles -(function outer (modules, cache, entry) { +(function outer (modules, cache, entry, global, hasExports, erName) { // Save the require from previous bundle to this closure if any - var previousRequire = typeof require == "function" && require; + var previousRequire = typeof global[erName] === "function" && global[erName]; function newRequire(name, jumped){ if(!cache[name]) { @@ -17,7 +17,7 @@ // if we cannot find the module within our internal map or // cache jump to the current global require ie. the last bundle // that was added to the page. - var currentRequire = typeof require == "function" && require; + var currentRequire = typeof global[erName] === "function" && global[erName]; if (!jumped && currentRequire) return currentRequire(name, true); // If there are other bundles on this page the require from the @@ -37,8 +37,12 @@ } return cache[name].exports; } + + // Override the current require with this new one. This has to happend + // before we requires anything so cross bundle requiring works both ways. + if (hasExports) global[erName] = newRequire; + for(var i=0;i