What are some disadvantages associated with using namespaces in Typescript/JavaScript?

After reading various articles on the internet and hearing arguments against namespaces, I am still unsure about the benefits of using modules with a module loader instead. Some claim that namespaces are outdated and problematic, but I'm not convinced by these points. Can someone provide real-world examples to support these arguments?

  • People argue that namespaces create at least 1 global variable. But why is that considered a problem? Personally, I don't see any harm in having a global variable like 'angular'.
  • Some say that modules allow consumers to name imported variables as they wish. But how common is it for there to be duplicate variable names like 'angular'? And in cases where duplicates do occur, can't we simply rename one of them without much trouble?

  • Another argument is that module loaders make bundling scripts easier by organizing them in the correct order. However, couldn't this order also be achieved by manually arranging imports at the top of each file or using tools like Typescript's "outFile" option in tsconfig.json?

  • There's also the claim that module loaders improve performance. But if I end up with a single large JavaScript file either way, will the difference in performance really be significant? Even with dynamic loading, does the incremental loading of a few kilobytes make a noticeable impact?

  • Finally, even if modules and module loaders are superior to bundling and referencing in HTML, wouldn't using a module loader for building a library require users to install the loader dependency as well?

Thank you all for your insights.

Answer №1

Currently, using namespaces in JavaScript is generally considered a questionable practice for several reasons. These same concerns also apply to TypeScript since it essentially builds on top of JavaScript.

While you have mentioned some of these reasons yourself, their importance may not be immediately apparent. Allow me to delve into them further.

Implicit Relationship Ordering

By utilizing namespaces in your code with external libraries, you inadvertently create dependencies between your code and the libraries being used.

This results in either manually managing these dependencies to ensure correct loading sequences or relying on compiler/bundler instructions for proper arrangement.

Such an approach introduces an extra layer of complexity that is prone to errors. What if at some point you decide to cease using a certain library? Will you remember to exclude it properly? It is more efficient to let tools handle such tasks.

Namespace Collision

Global namespacing often leads to conflicts, as exemplified by instances like lodash vs underscore.

Versioning within Namespaces

Akin to namespace collision, conflicts can arise when different versions of a library are utilized by both your code and another dependency. This raises the question of which version should take precedence in the global namespace.

Modules provide a solution to this predicament.

(note: TypeScript's typing system currently struggles with handling multiple versions adequately, potentially resulting in issues that necessitate workarounds.)

Lack of Tree Shaking Capability

Through ESM, bundlers like rollup and webpack enjoy the ability to perform tree-shaking, efficiently removing unused code segments. However, employing libraries via namespaces fails to provide necessary information for the bundler to conduct such optimizations.

Inflexibility

Exposing your library through namespaces lays bare its internal structure, making any refactoring efforts pose the risk of breaking changes for consumers.

While workarounds like careful creation of adapters or aliases exist, they only add complexity to your codebase and typically lead to disarray.

Security Concerns

The debate over security emerges when considering the exposure of your code in the global namespace, as it opens up possibilities for unauthorized access and manipulation by external sources.

These points represent just a fraction of the multitude of reasons against using namespaces, but they serve as a good starting point for discussion.

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

Autocomplete failing to provide a valid response, returning a null value instead

Utilizing an Autocomplete feature for employee search, users can input a name and select from the list of results. However, the current onChange function logs the index value instead of the selected employee's name. Is there a way to pass the employee ...

Create a unique onblur event listener for every element in a loop in Javascript

https://i.sstatic.net/tRYul.png I have added several items to a column in the database, but I am unsure of how to implement an onblur function for validation for each item within a loop. For example, if the NAME field is empty, I want to display an alert ...

Tips on executing a $.get request while submitting a form?

Instead of using AJAX to submit my form, I am trying to implement a progress bar by making GET requests to the server while the form is submitting. This is particularly important when dealing with multiple file uploads that may cause the submission to take ...

Why is there a node_modules folder present in the npm package I authored when using it as a dependency in another module?

After successfully launching my first npm package, I noticed something strange when installing it as a dependency in my project. Upon exploring the project folder in node_modules, I discovered an unexpected node_modules folder containing just one package ...

Navigating to a URL using "res.render" following the process of fetching POST data from the DOM array in Node.js

Despite browsing through numerous related questions, I am still unsure about the best approach to render a URL after the frontend JavaScript collects DOM data and sends a POST request to an Express server's POST URL. I understand that fetch POST does ...

Prevent the upward arrow from appearing on the first row and the downward arrow from appearing on the last row when

This is a straightforward question, but I'm unsure how to achieve it. I am currently working on sorting columns using jQuery. $(document).ready(function(){ $(".up,.down,.top,.bottom").click(function(){ var row = $(this).parents("tr:f ...

Is Express capable of serving static files from a hidden folder with dot file?

I have set up my app to serve a static folder in the following way: app.use('/static', serveStatic(__dirname + '/view/my/static/folder')); Now, I am wondering how to configure the server to serve a hidden folder. For example, if I hav ...

Leverage NodeJS data within Angular framework

I am working with the following route: Server app.get('/claim/:id', compact.js(['global']), indexController.claim); module.exports.claim=function(req,res){ res.render('claim-note', { title: 'claim', noteId:req. ...

Using React with Axios to trigger several requests with a single action

Let's say a user selects a team from a dropdown menu, triggering a request to an API endpoint. const selectHomeTeamStat = evt => { const { value } = evt.target; getStats(leagueId, value, 'home'); }; In this hypothetical scen ...

Customize default progress bar in browsers

One feature of my website allows users to update their personal information, profile image, background image, and more. After clicking the submit button, a loading screen appears with a progress percentage displayed at the bottom left corner of the page (i ...

Using Javascript regex to remove spaces inside parentheses

Can you provide the specific Javascript regex code for removing spaces only within parentheses? Take for instance: balance( 11010000 ) / balance( 11050000 ) The desired output should be: balance(11010000) / balance(11050000) ...

Can we verify if this API response is accurate?

I am currently delving into the world of API's and developing a basic response for users when they hit an endpoint on my express app. One question that has been lingering in my mind is what constitutes a proper API response – must it always be an o ...

Navigate to the end of a container

Is there a method to automatically scroll to the bottom of a div when the page is loaded? I have attempted several solutions without success. If you have any insights, please share them. Thank you! ...

Can an L1 VPC (CfnVpc) be transformed into an L2 VPC (IVpc)?

Due to the significant limitations of the Vpc construct, our team had to make a switch in our code to utilize CfnVpc in order to avoid having to dismantle the VPC every time we add or remove subnets. This transition has brought about various challenges... ...

Retrieve a HashMap through an HTTP GET request using Angular 10

I am currently using the following versions: Angular CLI: 10.0.1 Node: 12.18.2 OS: win32 x64 Angular: 10.0.2 In my setup, I have a Java Spring Boot service that is functioning correctly and returns data as a HashMap. Map<String, List<String>&g ...

Looking to display a div with both a plus and minus icon? Having trouble getting a div to show with left margin? Need assistance hiding or showing div text

Can someone please review this source code? Here is the demo link: http://jsfiddle.net/bala2024/nvR2S/40/ $('.expand').click(function(){ $(this).stop().animate({ width:'73%', height:'130px' }); $( ...

Leveraging the keyword 'this' within an object method in node's module.exports

My custom module: module.exports = { name: '', email: '', id: '', provider: '', logged_in: false, checkIfLoggedIn: function(req, res, next){ console.log(this); } }; I inclu ...

Determine if the user's request to my website is made through a URL visit or a script src/link href request

Presently, I am working on developing a custom tool similar to Rawgit, as a backup in case Rawgit goes down. Below is the PHP code I have created: <?php $urlquery = $_SERVER['QUERY_STRING']; $fullurl = 'http://' . $_SERVER['SE ...

What steps should I take to create an Onboarding/Walkthrough page using Angular Material Design?

Looking for guidance on creating an Onboarding/Walkthrough in Angular Material Design for Electron. As a newcomer to Angular, I'm aiming for a desktop application similar to the image provided. It should showcase several images and offer page navigat ...

Typescript object property continues to give undefined value despite object being fully populated

In my class called ParametrosEscaner, the structure is as follows: export enum TiposPixel { BlancoNegro = 0, Grises, Color }; export class ParametrosEscaner { tipoPixel: TiposPixel; resolucion: number; duplex: boolean; mostrarInterfaz: bool ...