We ran into an interesting problem in an existing project,
- We're using requireJS
- All our modules are AMD compliant(and we have a lot of them)
- We need to include a subset of
babel-polyfillas an AMD module to the project. - It's not possible to manually add this dependency to all modules one by one
- Our code is optimized and bundled using
r.js
Our main file looks something like this : // main.js
require(
[
'router',
'someOtherModule', /* In reality we have quite a few more here */
], function(Router, AppModule) {/*... app code ...*/}
)
So we'd like to load this polyfill module before any other module is loaded in main.js
What won't work :
- Shim - Shim is used for non AMD module.
- Adding the polyfill to the list above
router- in the minified code that r.js spits out, there's no guarantee thatpolyfillwill actually be in the code beforerouter, it's not the defined behavior and thus cannot be counted on. - Wrapping everything with another
require['polyfill']call seems to screw up the r.js optimizer, it won't seem the bundle together the other modules if they're wrapped inrequire[]. - Since the
polyfillis an AMD module, we can't just include it in the<HEAD>
Option 3 is still something we're investigating to see if it's possible.
So the question is - Is what we're trying to do possible?
Whenever I load polyfills I always always always load them in a
scriptelement inhead. I never load them through RequireJS. Loading them through RequireJS gives rise to all kinds of problems, as you discovered. You wrote:The
babel-polyfillpackage builds itself into a script that can be loaded through ascriptelement by using Browserify:If you inspect
dist/polyfill.js, you'll see it is not an AMD module. (Thedefinefunction it calls is not AMD'sdefinefunction.)You should be able to adapt this method to your whatever subset of
babel-polyfillyou use.