简体   繁体   中英

Module loading order in requirejs

We ran into an interesting problem in an existing project,

  1. We're using requireJS
  2. All our modules are AMD compliant(and we have a lot of them)
  3. We need to include a subset of babel-polyfill as an AMD module to the project.
  4. It's not possible to manually add this dependency to all modules one by one
  5. 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 :

  1. Shim - Shim is used for non AMD module.
  2. Adding the polyfill to the list above router - in the minified code that r.js spits out, there's no guarantee that polyfill will actually be in the code before router , it's not the defined behavior and thus cannot be counted on.
  3. 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 in require[] .
  4. Since the polyfill is 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 script element in head . I never load them through RequireJS. Loading them through RequireJS gives rise to all kinds of problems, as you discovered. You wrote:

Since the polyfill is an AMD module, we can't just include it in the <HEAD> .

The babel-polyfill package builds itself into a script that can be loaded through a script element by using Browserify:

#!/bin/sh
set -ex

BROWSERIFY_CMD="../../node_modules/browserify/bin/cmd.js"
UGLIFY_CMD="../../node_modules/uglify-js/bin/uglifyjs"

mkdir -p dist

node $BROWSERIFY_CMD lib/index.js \
  --insert-global-vars 'global' \
  --plugin bundle-collapser/plugin \
  --plugin derequire/plugin \
  >dist/polyfill.js
node $UGLIFY_CMD dist/polyfill.js \
  --compress keep_fnames,keep_fargs,warnings=false \
  --mangle keep_fnames \
  >dist/polyfill.min.js

If you inspect dist/polyfill.js , you'll see it is not an AMD module. (The define function it calls is not AMD's define function.)

You should be able to adapt this method to your whatever subset of babel-polyfill you use.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM