RequireJS sometimes fails to load jQuery

2019-02-27 09:41发布

问题:

My project structure looks like this

root/
  lib/
  js/

In my js folder I have a require-config file which references javascript-files in the lib directory. Like so:

require.config({
    paths: {
        jquery: ["../lib/jquery/dist/jquery"],
    }
});

Initiated in view like so:

<script data-main="js/require-config" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.1/require.min.js"></script>
<script>require(["viewModels/searchViewModel"]);</script>

And this is how my searchViewModel looks like (omitted code inside function), generated from typescript:

define(["require", "exports", "jquery"], function (require, exports, $) {
    "use strict";
    var SearchViewModel = (function () {
        function SearchViewModel() {
        }
        return SearchViewModel;
    }
});

For most of the time, there seems to be no problem finding the correct file. Occasionally though, it is looking for the jquery file in /js/jquery.js which will cause the browser to throw a 404 for http://localhost/js/jquery.js.

Am I doing something wrong in the require config? And how come it works sometimes and sometimes not?

回答1:

Do not use data-main to load your RequireJS configuration. The reason it works intermittently is because data-main causes RequireJS to load named script asynchronously. So by the time require(["viewModels/searchViewModel"]); executes, your configuration has not necessarily been loaded.

Using data-main to load configuration is safe only when all the code that depends on this configuration is loaded through the same file you pass to data-main. This could be because you've built a bundle that contains all the modules of your app plus the configuration, or because you use only deps in the configuration to load modules after the configuration is loaded.

Your case is not safe because you have code outside the module you load through data-main that depend on the configuration being loaded.

Split your script like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.1/require.min.js"></script>
<script src="js/require-config.js"></script>