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?
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>
RequireJS has been a hugely influential and important tool in the JavaScript world. It's still used in many solid, well-written projects today.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With