Permalink
Browse files

fix(index): cache loading Promises and fix lazy loading

fixes #15
  • Loading branch information...
niieani committed Jul 28, 2016
1 parent 0accfaf commit 26e1a744b060f2afaf515a76856758edb6058a06
Showing with 41 additions and 21 deletions.
  1. +41 −21 src/index.js
View
@@ -53,6 +53,7 @@ export class WebpackLoader extends Loader {
this.moduleRegistry = Object.create(null);
this.loaderPlugins = Object.create(null);
this.useTemplateLoader(new TextTemplateLoader());
this.modulesBeingLoaded = Object.create(null);
let that = this;
@@ -81,35 +82,54 @@ export class WebpackLoader extends Loader {
};
}
_getActualResult(result, resolve, reject) {
try {
const isAsync = typeof result === 'function' && /cb\(__webpack_require__/.test(result.toString());
if (!isAsync) {
return resolve(result);
} else {
// because of async loading when the bundle loader is active
return result(actual => resolve(actual));
}
} catch (e) {
reject(e);
}
}
_import(moduleId) {
if (this.modulesBeingLoaded[moduleId]) {
return this.modulesBeingLoaded[moduleId];
}
const moduleIdParts = moduleId.split('!');
const path = moduleIdParts.splice(moduleIdParts.length - 1, 1)[0];
const loaderPlugin = moduleIdParts.length === 1 ? moduleIdParts[0] : null;
return new Promise((resolve, reject) => {
try {
if (loaderPlugin) {
resolve(this.loaderPlugins[loaderPlugin].fetch(path));
} else {
try {
const result = __webpack_require__(path);
resolve(result);
return;
} catch (_) {}
require.ensure([], function(require) {
const result = require('aurelia-loader-context/' + path);
if (typeof result === 'function') {
// because of async loading when the bundle loader is active
result(res => resolve(res));
} else {
resolve(result);
}
}, 'app');
const action = new Promise((resolve, reject) => {
if (loaderPlugin) {
try {
return resolve(this.loaderPlugins[loaderPlugin].fetch(path));
} catch (e) {
return reject(e);
}
} catch (e) {
reject(e);
}
else {
try {
// first try native webpack method //
const result = __webpack_require__(path);
return this._getActualResult(result, resolve, reject);
} catch (_) {}
require.ensure([], function(require) {
// if failed, try resolving via the context created by the plugin //
const result = require('aurelia-loader-context/' + path);
return this._getActualResult(result, resolve, reject);
}, 'app');
}
}).then(result => {
this.modulesBeingLoaded[moduleId] = undefined;
return result;
});
this.modulesBeingLoaded[moduleId] = action;
return action;
}
/**

0 comments on commit 26e1a74

Please sign in to comment.