Requirejs - Configuring require before loading dat

2019-03-29 01:07发布

问题:

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?

回答1:

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.