From 674b17d732c492c847fbbc943ab44adab2e78625 Mon Sep 17 00:00:00 2001 From: Devon Govett Date: Thu, 3 May 2018 17:08:38 -0700 Subject: [PATCH] Fix loading modules with AMD defines (#1285) --- src/assets/JSAsset.js | 2 +- src/visitors/globals.js | 7 ++++++- test/integration/define-amd/index.js | 7 +++++++ test/javascript.js | 12 ++++++++++++ 4 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 test/integration/define-amd/index.js diff --git a/src/assets/JSAsset.js b/src/assets/JSAsset.js index f4231b73c12..167db8e23eb 100644 --- a/src/assets/JSAsset.js +++ b/src/assets/JSAsset.js @@ -15,7 +15,7 @@ const SourceMap = require('../SourceMap'); const IMPORT_RE = /\b(?:import\b|export\b|require\s*\()/; const ENV_RE = /\b(?:process\.env)\b/; -const GLOBAL_RE = /\b(?:process|__dirname|__filename|global|Buffer)\b/; +const GLOBAL_RE = /\b(?:process|__dirname|__filename|global|Buffer|define)\b/; const FS_RE = /\breadFileSync\b/; const SW_RE = /\bnavigator\s*\.\s*serviceWorker\s*\.\s*register\s*\(/; const WORKER_RE = /\bnew\s*Worker\s*\(/; diff --git a/src/visitors/globals.js b/src/visitors/globals.js index 2b2e5a4a3f8..f84cde3028d 100644 --- a/src/visitors/globals.js +++ b/src/visitors/globals.js @@ -13,7 +13,12 @@ const VARS = { Buffer: asset => { asset.addDependency('buffer'); return 'var Buffer = require("buffer").Buffer;'; - } + }, + // Prevent AMD defines from working when loading UMD bundles. + // Ideally the CommonJS check would come before the AMD check, but many + // existing modules do the checks the opposite way leading to modules + // not exporting anything to Parcel. + define: () => 'var define;' }; module.exports = { diff --git a/test/integration/define-amd/index.js b/test/integration/define-amd/index.js new file mode 100644 index 00000000000..296ed68fc15 --- /dev/null +++ b/test/integration/define-amd/index.js @@ -0,0 +1,7 @@ +if (typeof define === 'function' && define.amd) { + define(function () { + return 4; + }); +} else if (typeof module === 'object') { + module.exports = 2; +} diff --git a/test/javascript.js b/test/javascript.js index 6000d04ad16..addaf4df21c 100644 --- a/test/javascript.js +++ b/test/javascript.js @@ -884,4 +884,16 @@ describe('javascript', function() { const ctx = run(b, null, {require: false}); assert.equal(ctx.window.testing(), 'Test!'); }); + + it('should set `define` to undefined so AMD checks in UMD modules do not pass', async function() { + let b = await bundle(__dirname + '/integration/define-amd/index.js'); + let test; + const mockDefine = function(f) { + test = f(); + }; + mockDefine.amd = true; + + run(b, {define: mockDefine}); + assert.equal(test, 2); + }); });