Requirejs data-main does not work

Asked

Viewed 112 times

2

Hello

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

/Testerequire/jquery.js net::ERR_FILE_NOT_FOUND Error: Script error for "jquery" http://requirejs.org/docs/errors.html#scripterror

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

  • Testerequire
    • Components
      • jquery
        • dist
          • jquery.js
    • .bowerrc
    • app js.
    • Bower.json
    • index.html
    • require.js (require library)

Does anyone have any idea?

1 answer

2

The mistake happens because the jquery is not loaded at the time of execution.

According to the documentation of requirejs (in English):

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

and, also:

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

There are two solutions in this case:


1) As per the documentation, you can load the configuration script and leave it as a dependency for the 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) Place all configuration code within 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.