Understanding requireJs hello world example

requireJs hello world helps you to understand the flow of your module across the application. Using requireJs the java-script can be structured with modular approach.


requireJs is most commonly used by java-script applications such as Kendo UI and other major frameworks like WordPress, Drupal etc… requireJs is a modularity based architecture which will help maintain the code for the developer to the ease of access and understanding.

Understanding when and how to use

define() and require() which utilize requireJs library and these are the only methods to be used across your applications for incorporating modular approach. define() is used to define a module and require() is used to asynchronously load the javascript for the first time. HTML will understand the data-bind attribute of SCRIPT tag to identify initialized javascript for example it will be “js/main” and SRC of it will be “require.js”.

A realistic example for using requireJs is that, consider a scenario where your application is using  jQuery as the library and there are form fields which are email and phone number fields. To validate email and phone number using  jQuery library you need to load jQuery before rendering email and mobile number validator modules. Since email and phone number are dependent on jQuery it should be loaded prior.

Here you should use define() method to build email and phone number validator function, which are called as modules. require() method should be used in main javascript file which will be use in data-bind ATTRIBUTES.

Hello World example

Step 1 : Create or define a folder structure to place your modules and third-party libraries. In my application I have defined my JS structure as below,

Step 2 : Create a HTML file in your to initialize the main.js and name that HTML as index.html copy-paste the content given below,

Step 3 : world module is dependent on hello module so the order of the module called is important.Open main.js copy-paste the content given below,

Step 4 : Creating hello module. Open module/hello.js copy-paste the content given below,

Step 5 : Creating world module. Open module/world.js copy-paste the content given below,

If you run your index.html in your browser you will see the browser output as “Hello World !”.

Let us know your feedback on the article.

Leave a Comment

Your email address will not be published. Required fields are marked *