I am using require.js to load some JS libraries and want to run some common code before and after load. I have made a simple loader plug-in named plug.js
to do so:
define([], function () {
return {
load: function (name, req, onload, config) {
// Pre-load code...
req([name], function (value) {
// Post-load code...
onload(value);
});
}
};
});
When I use it from other modules like this, it works as expected:
define(['plug!lib1'], function (lib1) {
// Use lib1
}
But I want to prevent the library to be accidentally loaded with the default loader, so I tried to add the following mapping:
require.config({
// ...
map: {
'*': {
'lib1': 'plug!lib1'
}
},
// ...
}
Then I required the library in my modules without specifying the plug-in by define(['lib1'], ...)
and the pre-load code of the plug-in runs as expected, but the post-load code never runs and I get load timeout errors. I also tried to apply mapping to specific modules rather than to *
, but got the same error.
Is it something wrong with my loader plug-in code? Is it ever possible to have the default loader plug-in associated with a module (a global plug-in would also be acceptable)?
As an alternative I see making custom modules with pre-load code and setting them as dependencies in shim configuration, but this looks even less convenient than specifying the plug-in name everywhere.
Looks like require.js tries to prevent circular dependency. app
module requests lib1
, which resolves to plug!lib1
, and plug
requests lib1
again, which require.js refuses to load despite that this time it would be loaded directly rather than plug
would be called recursively.
I renamed the original library, and the problem gone away:
require.config({
// ...
paths: {
'lib1-core': 'lib1'
},
map: {
'*': {
'lib1': 'plug!lib1-core'
}
},
// ...
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.