"An auto-invoking function is declared in a TypeScript compiled module with a var statement

Currently, I am in the process of converting an existing AngularJS (1.x) project to TypeScript. The code seems to be functioning properly, but there are some aspects that leave me with questions.

In JavaScript, I declare a module like this:

(function() {
    'use strict';
    angular.module('myModule', []);
})();

In TypeScript, the declaration looks like this:

module myModule {
    'use strict';
    angular.module('myModule', []);
}

This is then compiled to:

var myModule;
(function (myModule) {
    "use strict";
    angular.module("myModule", []);
})(myModule || (myModule = {}));

I have a few uncertainties:

  1. Is it incorrect to introduce var myModule into the global scope?
  2. Why is myModule passed into the anonymous function?
  3. Considering the addition of var myModule, should I avoid overwriting it when declaring other components such as Controllers? Would using a different module name be more appropriate here?

In essence, can the same name be reused for another module, like so:

module myModule {
    angular
      .module('myModule')
      .controller('myController');
}
// potentially overwriting the existing var myModule

Alternatively, would it be wiser to utilize a separate name for the new module, for instance:

module myModuleController {
    angular
      .module('myModule')
      .controller('myController');
}
// generating a distinct var myModule

The functionality appears unaffected regardless, but I believe that there may be important considerations regarding this matter that I should be aware of.

Answer №1

The purpose of this is to allow you to access the module from various other locations. For example:

module ModuleA {
    export var num = 4;
}

module ModuleB {
    export function log() {
        console.log(ModuleA.num);
    } 
}

You can also continue adding more to the same module:

module ModuleA {
    export var num = 4;
}

module ModuleA {
    export var str = "string";
}

console.log(ModuleA.num); // 4
console.log(ModuleA.str); // string

In the compiled JavaScript in your scenario, `myModule` is passed so that the new definitions are added to the existing module if it exists, or `{}` if not.
The compiled JavaScript in my (2nd) example looks like this:

var ModuleA;
(function (ModuleA) {
    ModuleA.num = 4;
})(ModuleA || (ModuleA = {}));
var ModuleA;
(function (ModuleA) {
    ModuleA.str = "string";
})(ModuleA || (ModuleA = {}));

As shown in the second instance, `ModuleA` is not empty, and therefore adding the `str` variable will be done within the previously defined module.

It's important to note that this behavior applies only when a module system is not being used, as seen in this example:

export module ModuleA {
    export var num = 4;
}

This code compiles into:

define(["require", "exports"], function (require, exports)
{
    "use strict";
    var ModuleA;
    (function (ModuleA) {
        ModuleA.num = 4;
    })(ModuleA = exports.ModuleA || (exports.ModuleA = {}));
});

(when using the default module system)

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

Strategies for handling user typos in a JavaScript prompt

Hi there! Just wanted to say that I'm new to this website, so please forgive any posting mistakes I might make. I'm currently taking a web technology class where we're learning JavaScript. In a previous lesson, we covered HTML5 and CSS. Our ...

Building a Modular Socket.io System using Express 4

I'm currently working on modularizing my application files, and I've encountered a challenge with the integration of Socket.io. My goal is to utilize io within my routes.js file. Here's an example of what I'm attempting: var router = r ...

Altering the src attribute of an Iframe in real-time

Local storage value needs to be passed into iframe URL using proper syntax. The code snippet below demonstrates the attempt: <script> // Get value from localstorage var x = localStorage.getItem("firstname"); // Display alert with stored val ...

Tips for modifying HTML template code within a Typescript document using Atom

There appears to be a current trend in Angular development where the template code is embedded within the Angular component, usually found in a Typescript or Javascript file. However, when attempting this approach, I noticed that I am missing html syntax ...

Facing an obstacle in Angular as I am unable to view my data

How can I bind the model of my controller in the init function and see the data when the init is called? Index.html <!DOCTYPE html> <html ng-app="I-Sign"> <head> <meta http-equiv='X-UA-Compatible' content='IE=edge&apo ...

Unable to retrieve embedded link using fetchText function in casperjs

Exploring the capabilities of Casperjs provides a valuable opportunity to test specific functions across different websites. The website used in this scenario serves as a tutorial illustration. An interesting challenge arises with an embed code that cann ...

JavaScript can retrieve the default page name that is hidden within the browser's URL

When a URL is entered without a specific file name at the end, such as "www.google.com," the server typically serves a default file like "index.html" or "default.aspx." In this scenario, if the browser displays "www.google.com," I am looking to extract the ...

sinon: Techniques for stubbing an entire class as opposed to singular methods

I am faced with a situation where I have a class that instantiates another class in my test. My goal is to stub out the entire second class, ensuring that its constructor is never invoked. Consider the following scenario: Test.js class Test { construct ...

Interactive image sliders in a Netflix-inspired style with live previews on hover, fully compatible with Bootstrap framework

I'm looking for suggestions on Twitter Bootstrap compatible jquery plugins that can create a Netflix-style continuously scrolling image carousel with mouse-over functionality. I've tried the carousel included in the Bootstrap JS library, but it r ...

Saving components locally (vue2)

Looking for help with passing data from Props to Data in vue.js? Check out this Stack Overflow discussion. If you're running into issues, take a look at this sandbox example: https://codesandbox.io/s/u3mr8. Concerned about side effects of copying ob ...

Changing images in vuejs

I am seeking to achieve a seamless transition between two images along with a corresponding legend. These images are sourced from an object-array collection. Since transitions operate only on single tags and components, I have devised a component to encap ...

Modify the Radio component in Material UI to customize the color of the checked

After researching various threads on the topic, I am still unable to modify the default red checked color in material ui. Below is the code snippet in question: return ( <FormControl> <FormLabel>{label}</FormLabel> ...

Transforming with Babel to create pure vanilla JavaScript

Our current development process involves working with a custom PHP MVC Framework that combines HTML (Views), PHP files, and included JS with script tags (including JQuery, Bootstrap, and some old-fashioned JS libs). During the development stages, we want ...

Receive a list of articles based on your subscription status

I am looking to create a filter that can retrieve subscription records Entity 'Subscription' export class Subscription { @PrimaryColumn() id: string; @Column('uuid') userId: string; @Column('uuid') targetUserId: s ...

How to access individual reactive form instances within an ngFor loop in Angular

I've been grappling with this issue for a few hours now, trying to find a solution that doesn't involve adding fields dynamically. All I need is the ability to access the properties of each form instance, but currently, it only displays one insta ...

Execute Validation Function on Every TextField and Radio Button

I'm new to Javascript and struggling to make my function work for both radio buttons and text fields. Here is the HTML code for the form: <form action="sendmail.php" method="post" name="cascader" onsubmit="prepareEventHandlers()" id="cascader"&g ...

Having trouble getting NextJS to work with jsmpeg/node-rtsp-stream for displaying an RTSP stream

Exploring: https://github.com/kyriesent/node-rtsp-stream and How to display IP camera feed from an RTSP url onto reactjs app page? I attempted to showcase the RTSP stream from a CCTV but encountered an error. ReferenceError: document is not defined at scri ...

One-time export feature similar to Typescript's export_once functionality

When I have the following code structure: File1.ts function someFunction(){...} export default someFunction(); and then File2.ts import File1 from "./File1"; File3.ts import File1 from "./File1"; My question is, will the export de ...

What steps can be taken to rectify the issue with the table during the export to

I am using a library called DataTable to present my data in a table format. The DataTable has buttons on the header, one of which allows exporting the data into an Excel file. However, when I try to open the exported data in Excel, I encounter an error sta ...

What is the best way to ensure every component in Angular 2 has access to a custom pipe?

I've come up with a unique idea to create a custom rainbowize pipe that wraps each letter in a span with a random color of the rainbow as the css color property. My goal is to implement this custom pipe across all components in my app without having t ...