From 19284857c50847544ad842054030e52c2e03d7a4 Mon Sep 17 00:00:00 2001 From: unscriptable Date: Wed, 12 Feb 2014 20:52:00 -0500 Subject: [PATCH] Handle when factory args > dependent module ids. e.g. define(['dep1', 'dep2'], function (dep1, dep2, dep3) {}); The curl/loader/cjsm11 cram plugin does this now! (see https://github.com/cujojs/curl/issues/253) --- lib/transform/amdToSimplifiedAmd.js | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/lib/transform/amdToSimplifiedAmd.js b/lib/transform/amdToSimplifiedAmd.js index 25fc999..0c84c44 100644 --- a/lib/transform/amdToSimplifiedAmd.js +++ b/lib/transform/amdToSimplifiedAmd.js @@ -89,8 +89,18 @@ define(function () { depList = ['require', 'exports', 'module'].slice(0, argList.length); } - if (argList.length < depList.length) { - // create placeholders at end + /* scenarios: + 1. factory args and module ids match (ideal case): + define(['dep1', 'dep2'], function (dep1, dep2) {}); + 2. more factory args than module ids (cjsm11 loader does this): + define(['dep1', 'dep2'], function (dep1, dep2, dep3) {}); + 3. more module ids than factory args (common user shortcut): + define(['dep1', 'dep2'], function (dep1) {}); + */ + + if (depList.length > argList.length) { + // there are more module ids than factory args, + // so create placeholders at the end of factory args. argList = depList.map(function (dep, i) { return i in argList ? argList[i] : idToVar('', i); }); @@ -99,8 +109,12 @@ define(function () { if (requires.length > 0) { reqIds = requires.map(function (req) { return req.id; }); reqVars = requires.map(function (req) { return req.varName; }); + // if there are more factory args than module ids, then dev + // may have intended the extra args to be undefined. we need + // to insert before these or the arguments won't match the + // module ids! also: cjsm11 loader does this to shadow `define`. + argList.splice.apply(argList, [depList.length, 0].concat(reqVars)); depList = depList.concat(reqIds); - argList = argList.concat(reqVars); } return 'define('