The syntax comparison between CommonJS and AMD modules in a modular AngularJS application

Apologies if this question has already been addressed, but I couldn't find any relevant information. Currently, I'm in the process of refactoring a large AngularJS application by creating components as AMD modules. The build process (grunt) utilizes the requirejs plugin to load and concatenate all the modules into a single JS file along with jQuery.

Recently, I came across CommonJS syntax which seems cleaner compared to AMD. I'm considering switching to CommonJS modules from AMD, especially since the build process would be similar, just replacing requireJS with browserify.

Are there any specific advantages of using AMD modules over CommonJS in my workflow? Can asynchronous module loading still be beneficial at runtime when bundling all modules into a single JS file?

Thank you for your insights.

Answer №1

These days, I recommend looking into ES2015 modules as the native module system in JavaScript. It combines the simplicity of syntax from CommonJS and the ability to load modules asynchronously like AMD.

// my-module.js
export const foo = "foo";
export function bar() { return "bar"; };

...

// main.js
import { foo, bar } from "./my-module.js";
console.log( foo, bar() );

Natively supported only by Chrome 60+ at the moment, but you can make it work in any browser with Webpack or SystemJS. I personally prioritize progressive enhancement and strive to deliver core user experiences quickly. I appreciate being able to combine compiled synchronous and loaded asynchronous modules in one application for optimal performance (thanks to Webpack). This way, you have control over which modules get compiled into a single file and which ones are loaded on demand.

Promise.all([
 import("./module-foo" ),
 import("./module-bar" ),
 import("./module-baz" )
]).then( moduleExports => {
  console.log( moduleExports );
}).catch(( e )=> {
  console.error( e );
});

In my blog post, I discuss how to achieve this setup in detail: https://medium.com/@sheiko/state-of-javascript-modules-2017-6548fc8af54a. Enjoy!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a modal with a checkbox option for "remember my preference" in Angular

Currently, I am working on an Angular project (version 16) and my goal is to create a dialog modal that includes a checkbox for "do not show again". Here is the process I envision: When a user visits the web application for the first time, a dialog moda ...

Is it possible to save data to a file using React?

As I work on a React web application, the need has arisen to store crucial user data on the client side in a stable manner. Due to the requirement of data stability and the constraint against using Indexed DB, I am considering storing the data as JSON in ...

Storing formatted user input in an array with VueJS: A step-by-step guide

Looking for assistance that relates to the following question Vue.js: Input formatting using computed property is not applying when typing quick I am facing a challenge in extracting formatted values from text inputs and storing them in an array. I intend ...

Is the synchronicity problem causing a bug in my JavaScript code?

Steps to Reproduce the Issue: Go to Enter sMqNFAU0tOw (or any other Youtube video ID) in the Video Playlist Click on Play Videos! The JavaScript console should display an error message like Uncaught TypeError: undefined is not a function This error is ...

Converting a JSON PHP array into Javascript

How can I convert this PHP array named $data into JSON using json_encode? Whenever I try to do so in JavaScript by writing... var myJson = <?php echo json_encode($data) ?>; console.log(myJson); I encounter errors. I am curious about any restrictio ...

Prevent caching in browser for JavaScript GET requests

My service includes a feature that adds Cache header to responses in order to allow browser caching. However, there are certain JavaScript requests where I need to ensure the data is force reloaded, bypassing the browser cache. Is there a way to accompli ...

Convert numbers to words in the Indian currency format as you type up to a 16-digit number, displaying the Indian rupees symbol automatically without the need to click a button

How can we modify the code below to automatically add the Indian rupees symbol in the input field? https://i.sstatic.net/TlNLc.png $('.allow_decimal').keyup(function (event) { $(this).val(function (index, value) { return valu ...

Uncertainty surrounding $q and commitments

After spending several hours researching Kris Kowal's Q library and the angularjs $q variable, I am still struggling to comprehend how it all works. Currently, my service contains the following code: resetpassword: function (email, oldPassword, newP ...

Swapping out a character on a webpage using jQuery

Can someone help me remove the colon from this code snippet on my webpage? <h1><b>Headline:</b> something</h1> I'm looking for a simple solution using jQuery, as I am a beginner in JavaScript. Please include the complete code ...

Using AngularJS to bind objects with a checkbox

I am dealing with a nested list of objects that can go up to three levels deep. Each object contains another nested object, and this nesting can continue to multiple levels. I am interested in binding these objects directly to checkboxes so that when I che ...

Retrieve the entity object and convert it into JSON format using json_encode

I have an array that looks something like this: $general_informations['company'] = $company_db In this array, $company_db is an Entity object with properties, such as: $city = $company_db->getCity(); After using json_encode(), I want to re ...

Obtaining HTML elements from JSON using jQuery (i.e., the opposite of serializing with Ajax)

I am looking to extract values from a set of controls (INPUT, SELECT, TEXTAREA) within a DIV and send them as JSON via Ajax to a server. Utilizing jQuery's serializeArray makes this process easy. After sending the JSON data, I expect the server to re ...

Generating a list of objects from MongoDB using Node.js

Hello everyone, I am currently learning about mongodb and node js for the first time, so please bear with me if my question is too basic. I am working with a schema that looks like this: var mongoose = require('mongoose'); var CatSchema = new m ...

jQuery's AJAX feature fails to identify the newly modified div classes

For my new website, I am developing a simple checklist feature. To handle the check and uncheck requests from users, I'm using jQuery's $.ajax() function. Whenever a user clicks on the check or uncheck buttons, jQuery retrieves the validation tok ...

Align an element at the center of both the x and y axes using CSS

Imagine you have a div in an html document with absolute positioning, like this: <div style="position:absolute">Hello!</div> Now, if you want to set a specific X and Y position for the div (potentially using JQuery), it's pretty straight ...

"Encountering issues when trying to retrieve the initial element from an array using underscore.js

I am currently developing a backend website using Angular with minimal underscore.js usage. My backend is built on the PHP framework Laravel 4, which has proved to be very useful for me. However, I have encountered a problem: When querying a URL with Angu ...

Sending MVC3 model information as JSON to a JavaScript block

My challenge is to correctly pass my MVC3 model into a script block on the client side. This is the approach I'm taking in my Razor view: <script type="text/javascript"> var items = @( Json.Encode(Model) ); </script> The "Model" in t ...

Creating a background with image overlays in React: A step-by-step guide

My challenge is to have an image that covers the entire background but it seems to stop abruptly where another object is placed, unable to extend further. I am utilizing Material UI and here is a snippet of my code: import { Image } from "../images&q ...

Adjusting the slide display in angular-slick based on the window's width automatically

I am new to working with Angular and I'm trying to create a responsive slideshow using angular-slick. Here is an example of my code: <slick infinite="true" slides-to-show="4" slides-to-scroll="1" prev-arrow=".slick-prev" next-arrow=".slick-next"&g ...

I am unable to reach my pages through their URL directly, I can only access them through links within Next.js

My next JS application runs smoothly during development, but encounters an issue when published online. I can only access the pages through links on the home page that direct to those specific pages. For instance, trying to navigate directly to www.examp ...