TruMan1
TruMan1

Reputation: 36168

How to load jQuery Migrate for jQuery via RequireJS?

Can I load jQuery migrate via RequireJS? I don't understand how the timing can be handled correctly. See this example:

require([
  'jquery',
  'jqmigrate'
], function ($) {
  if ($.browser.msie) {...}
});

Isn't is possible that jqmigrate will load before jquery? Also, I do not want to keep loading jqmigrate explicitly in every module. Any way to do this in the require.config so it loads jqmigrate automatically when jQuery is required?

Upvotes: 5

Views: 3958

Answers (4)

Oleksii Shovhenia
Oleksii Shovhenia

Reputation: 3702

jquery-migrate-wrapper.js

    define(['jquery', 'jquery-migrate'], function ($) {
        // additional initialization logic can be added here
        $.UNSAFE_restoreLegacyHtmlPrefilter();
        return $;
    })

require-config.js

  require.config({
    ...otherConfigOptions,
    shim: {
      ...otherShimSettings,
      'jquery-migrate':{deps: ['jquery']},
    },
    map: {
      // provides 'jquery-migrate-wrapper' for all (*) modules that require'jquery'
      '*': { 'jquery': 'jquery-migrate-wrapper' },
      // but provides the original 'jquery' for 'jquery-migrate-wrapper' and       
      // 'jquery-migrate'
      'jquery-migrate-wrapper': { 'jquery': 'jquery' },
      'jquery-migrate': {'jquery': 'jquery'}
    }
  })

Upvotes: 0

Adam G
Adam G

Reputation: 21

jQuery Migrate 3.0.1 currently has a defect that renders it unusable for RequireJS or any AMD loader. A change is required to the UMD fragment before implementing the accepted answer:

define( [ "jquery" ], function ($) {
    return factory($, window);
});

Details and solution are here.

Upvotes: 2

Adam
Adam

Reputation: 2122

using shims worked for me. I did get stuck because i had pluralized shims its; shim

requirejs.config({
    paths: {
        'jquery': '//code.jquery.com/jquery-2.1.4',
        'jquery-migrate': '//code.jquery.com/jquery-migrate-1.2.1'
    },
    shim: {
        'jquery-migrate': { deps: ['jquery'], exports: 'jQuery' },
        'foo': ['jquery']
    }
});
require(['jquery-migrate', './foo'], ($, foo) => {
     console.log('bootstrapped', $, foo);
});

Upvotes: 4

u.k
u.k

Reputation: 3091

There are a couple of things you will need:

  1. make sure jqmigrate depends on jquery.
  2. you could write a wrapper module that include both, and return jquery, so your require.config could look like:

jquery-wrapper.js:

define(['jquery-src', 'jqmigrate'], function ($) {
  return $;
})

require.config

{
  paths: {
    'jquery-src' : '/path/to/jquery',
    'jqmigrate': '/path/to/jqmigrate',
    'jquery': '/path/to/jquery-wrapper'
  }
}

Upvotes: 4

Related Questions