Skip to content

Commit

Permalink
fix(bundler): improve compatibility with legacy libs that depends on …
Browse files Browse the repository at this point in the history
…jquery or momentjs

Special treatment for jquery and moment, put them in front of everything else, so that jquery and moment can create global vars as early as possible. This improves compatibility with some legacy jquery plugins.
Note as of momentjs version 2.10.0, momentjs no longer exports global object in AMD module environment. There is special code in lib/build/amodro-trace/write/defines.js to bring up global var "moment".
  • Loading branch information
3cp committed Feb 27, 2019
1 parent 2494f95 commit cd079a0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
7 changes: 7 additions & 0 deletions lib/build/amodro-trace/write/defines.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ function defines(options) {
config = context.config,
packageName = context.pkgsMainMap[moduleName];

if (packageName === 'moment') {
// Expose moment to global var to improve compatibility with some legacy libs.
// It also load momentjs up immediately.
_contents = _contents.replace(/\bdefine\((\w+)\)/, (match, factoryName) =>
`(function(){var m=${factoryName}();if(typeof moment === 'undefined'){window.moment=m;} define(function(){return m;})})()`
);
}

function onFound(info) {
if (info.foundId) {
Expand Down
19 changes: 18 additions & 1 deletion lib/build/bundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,24 @@ exports.Bundle = class {
};

bundleFiles.forEach(visit);
return sorted;

// Special treatment for jquery and moment, put them in front of everything else,
// so that jquery and moment can create global vars as early as possible.
// This improves compatibility with some legacy jquery plugins.
// Note as of momentjs version 2.10.0, momentjs no longer exports global object
// in AMD module environment. There is special code in lib/build/amodro-trace/write/defines.js
// to bring up global var "moment".
const special = [];
while (true) { // eslint-disable-line no-constant-condition
const idx = sorted.findIndex(f => f.dependencyInclusion && (
f.dependencyInclusion.description.name === 'jquery' ||
f.dependencyInclusion.description.name === 'moment'));

if (idx === -1) break;
special.push(...sorted.splice(idx, 1));
}

return [...special, ...sorted];
}

write(platform) {
Expand Down

0 comments on commit cd079a0

Please sign in to comment.