Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requirejs - Configuring require before loading data-main

We're using requirejs for the first time, and I'm having trouble structuring my dependencies.

I've defined my main app.js file as the data-main attribute in my index.html:

<script data-main="src/app" src="/js/lib/require/require.js"></script>

But, I have a file which defines all my require path/shim configurations, and I want that to run before the app.js file. I need it to run so that I can reference configured paths as dependencies in my app.js.

I don't think the right way is to put my config.js as the data-main. I tried setting the config.js as a dependency like this:

   <script type="text/javascript">
        var require = {
            baseUrl: "/",
            deps: ["src/config"]
        }
    </script>
    <!-- data-main is the main js file of the app -->
    <script data-main="src/app" src="/js/lib/require/require.js"></script>

but that didn't help.

Any suggestions?

like image 947
elanh Avatar asked Mar 03 '13 10:03

elanh


People also ask

What is RequireJS config?

Advertisements. RequireJS can be initialized by passing the main configuration in the HTML template through the data-main attribute. It is used by RequireJS to know which module to load in your application. For instance − <script data-main = "scripts/main" src = "scripts/require.js"></script>

Is RequireJS obsolete?

RequireJS has been a hugely influential and important tool in the JavaScript world. It's still used in many solid, well-written projects today.

What is require () in JavaScript?

require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object. require() statement not only allows to add built-in core NodeJS modules but also community-based and local modules.

What is data-Main in script tag?

data-main is for when you want to have a single entry point to your application. That single script line will load RequireJS along with scripts/main. js and kick off your app. The result of <script data-main="scripts/main" src="scripts/require.js"></script> is that <script async src="scripts/main.


1 Answers

In my case, I load config.js in app.js to share configuration for each pages.

For instance:

require(['config'], function(){
  require(['module','another'], function(){
    // run with all modules
  });
});

To optimize this project, using has.js is better way to reduce HTTP connection. For more detail, see this sample project.

like image 152
Kengo TODA Avatar answered Sep 22 '22 19:09

Kengo TODA