RequireJS data-main does not work

2

Hello

I'm always getting the same message when trying to run my index.html file that attempts to reload jQuery from requireJS.

  

/TestRequire/jquery.js net :: ERR_FILE_NOT_FOUND Error: Script error   for "jquery" link

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Test</title>
        <script data-main="app.js" src="require.js"></script>
    </head>

        <script>
        require(["jquery"], function($) {
            console.log($);
        });
        </script>

    <body></body>
</html>

app.js

requirejs.config({
    baseUrl: "components",
    paths: {
        "jquery": "jquery/dist/jquery",
        "bootstrap": "bootstrap/dist/js/bootstrap"
    },
    shim: {
        "bootstrap": {
            deps: ["jquery"]
        }
    }
});

Directory structure

  • TestRequire
    • components
      • jquery
        • dist
          • jquery.js
    • .bowerrc
    • app.js
    • bower.json
    • index.html
    • require.js (library require)

Does anyone have any ideas?

    
asked by anonymous 06.10.2016 / 15:58

1 answer

2

The error happens because jquery is not loaded at execution time.

According to the documentation for requirejs :

  

... This means that you can not assume that the load and execution of data-main will occur before all other scripts ...

and also:

  

... If you intend to use require within scripts defined in HTML, it is best not to use data-main

There are two solutions in this case:

1) According to the documentation, you can load the configuration script and leave it as a dependency for the load of jquery :

<script src="/lib/require.js"></script>

<!-- Carrega a configuração separadamente, fora do data-main -->
<script src="app.js" charset="utf-8"></script>
</head>
    <script>
    // === Cria a dependência ===
    require(['app.js'], function() {
        // === Executa a chamada do jquery ===
        require(["jquery"], function($) {
            console.log($);
        });
    });
 </script>

2) Put all the configuration code inside HTML:

<script>
// Configura.....
requirejs.config({
    baseUrl: "components",
    paths: {
        "jquery": "jquery/dist/jquery",
        "bootstrap": "bootstrap/dist/js/bootstrap"
    },
    shim: {
        "bootstrap": {
            deps: ["jquery"]
        }
    }
});

// Executa.....
require(["jquery"], function($) {
    console.log($);
});
</script>
    
06.10.2016 / 16:59