myHotTake

Tag: coding tips

  • How to Fix Circular Dependencies in Webpack with Ease

    Hey there! If you enjoy this little adventure through the world of JavaScript, feel free to like or share it with others.


    I decided to write a computer program, one line at a time. Each line was a character in my story, and like all good stories, each character had its own role to play. But as I wrote, I stumbled upon a peculiar problem: two of my characters were caught in a never-ending loop, constantly referencing each other without moving the story forward. This was my introduction to Webpack’s circular dependencies.

    Picture this: I’m crafting an epic tale where the hero, Line A, needs the wisdom of the sage, Line B, to defeat the villain. But surprise! Line B, in need of inspiration, turns to Line A. They keep sending each other on a quest for answers, but neither can continue their journey because they’re too busy pointing to one another. My story was stuck in a loop, much like a snake biting its own tail.

    To resolve this circular conundrum, I first needed to step back and rethink my narrative. I asked myself, “How can I break this cycle and let the story progress?” I realized I needed to introduce a new character, a mediator, to break the loop. By creating a third line, let’s call it Line C, I could have Line A and Line B send their messages through this neutral party. This intermediary could manage their exchanges without getting tangled in the repetitive cycle.

    As I wrote Line C into existence, the story began to flow smoothly again. Line A could seek the sage’s wisdom, and Line B could draw inspiration without falling back into the endless loop. My narrative now had the freedom to advance, and my characters could finally fulfill their destinies.


    As I sat back, satisfied with my narrative solution, I realized it was time to translate my story back into the world of JavaScript. Picture Line A and Line B as two JavaScript modules that depend on each other. This is how they looked in the code before I introduced Line C:

    // moduleA.js
    import { featureB } from './moduleB';
    export function featureA() {
      console.log('Feature A');
      featureB();
    }
    
    // moduleB.js
    import { featureA } from './moduleA';
    export function featureB() {
      console.log('Feature B');
      featureA();
    }

    As you can see, moduleA imports featureB from moduleB, and moduleB imports featureA from moduleA. This is our circular dependency.

    In my story, Line C became the mediator. In JavaScript, I could introduce a third module, moduleC.js, to break this cycle:

    // moduleC.js
    export function featureC() {
      console.log('Feature C');
    }
    
    // moduleA.js
    import { featureB } from './moduleB';
    import { featureC } from './moduleC';
    export function featureA() {
      console.log('Feature A');
      featureC();
      featureB();
    }
    
    // moduleB.js
    import { featureA } from './moduleA';
    import { featureC } from './moduleC';
    export function featureB() {
      console.log('Feature B');
      featureC();
      featureA();
    }

    Now, both moduleA and moduleB can use featureC from moduleC, creating a more balanced and manageable flow of logic without directly relying on each other.

    Key Takeaways/Final Thoughts:

    1. Identify the Cycle: Before solving circular dependencies, recognize where they occur. Use tools like Webpack’s circular dependency plugin to help spot these in your codebase.
    2. Refactor Thoughtfully: Introduce a new module or refactor the existing ones to mediate the dependencies, just like our Line C. This keeps your code modular and less tangled.
    3. Maintainability and Performance: Resolving circular dependencies not only makes your code more maintainable but also improves performance by reducing unnecessary imports and calls.
    4. Stay Creative: Just like storytelling, coding requires creativity. Approach your code with an open mind to find innovative solutions.
  • How Do JavaScript Notifications Mirror Swim Coaching?

    If you find this story helpful or entertaining, feel free to give it a like or share it with others who might enjoy it too!


    I’m a competitive swimmer, and my coach is eager to keep me informed about my performance and upcoming swim meets. Think of the Notification object in JavaScript as my coach’s way of sending me messages. Each message has several parts, much like a notification does.

    First, there’s the title of the notification. In swim terms, this is like my coach yelling, “Hey, there’s a meet this Saturday!” It’s the eye-catching bit that grabs my attention in the midst of my practice, much like how a title grabs the user’s attention when a notification pops up on their screen.

    Next is the body of the notification. This is akin to my coach diving into details about the meet: the location, the start time, and the events I’ll be swimming in. It’s the informative part that gives me context, just like how the body of a notification provides more information to the user.

    There’s also the icon, which could be compared to my coach waving his favorite swim towel or wearing a distinctive cap. It’s a visual cue that helps me quickly recognize who’s calling out to me, similar to how an icon in a notification helps users identify the source of the message at a glance.

    Additionally, there’s the tag, which is like my coach giving me a unique identifier for each meet or message. He might say, “This is about the Regional Championships,” distinguishing it from other messages I might receive. In the world of notifications, a tag can help group or replace existing notifications, ensuring clarity and organization.

    Lastly, there’s the actions part of a notification. This is similar to my coach giving me options on how to respond—perhaps suggesting I either confirm my attendance or ask questions about the meet. In JavaScript, actions provide users with options on what to do next, making the notification interactive.

    So, every time my coach communicates with me during training, it’s like receiving a well-structured Notification object, each component serving a specific purpose to keep me informed and prepared. Just as I rely on my coach’s messages to navigate the swimming world, developers use notifications to effectively communicate with users.


    In JavaScript, creating a Notification object is like my coach crafting the perfect message to keep me informed and ready for my swim meets. Here’s how we can create a notification, akin to how my coach communicates with me:

    // Check if the browser supports notifications
    if ("Notification" in window) {
      // Request permission to display notifications
      Notification.requestPermission().then(permission => {
        if (permission === "granted") {
          // Create a notification
          const notification = new Notification("Swim Meet Alert!", {
            body: "Regional Championships on Saturday at 10 AM. Don't forget your gear!",
            icon: "swim-icon.png",
            tag: "meet-2023",
            actions: [
              { action: 'confirm', title: 'Confirm Attendance' },
              { action: 'details', title: 'More Details' }
            ]
          });
        }
      });
    }

    Breaking it down:

    • Title: "Swim Meet Alert!" shouts to grab attention, just like my coach’s initial call.
    • Body: This part, "Regional Championships on Saturday...", provides the details, much like the specifics about the meet.
    • Icon: "swim-icon.png" serves as the visual cue, similar to my coach’s distinctive gear.
    • Tag: "meet-2023" is the unique identifier, ensuring that if another notification about the same meet comes through, it doesn’t add confusion.
    • Actions: These options, like ‘Confirm Attendance’, are interactive elements for the user to engage with, just as my coach might offer me choices.

    Key Takeaways:

    1. Purposeful Structure: Just as a well-structured message from a coach keeps a swimmer informed, a Notification object must be carefully structured to communicate effectively with users.
    2. Attention to Detail: Each component of the notification serves a specific purpose, ensuring clarity and engagement.
    3. User Interaction: Including actions within a notification encourages user interaction, enhancing the overall experience.
    4. Browser Compatibility: Always check for browser support and request permission to display notifications, ensuring that your message reaches the user effectively.
  • Unknown vs. Any in TypeScript: What’s the Real Difference?

    Hey there! If you find this story enlightening, feel free to give it a like or share it with someone who might enjoy it too!


    I’m in an ancient marketplace, with traders and storytellers. I’m on a quest to gather stories, and each storyteller here is like a data type, eager to share their tales. Now, I have two pouches: one embroidered with the word “unknown” and the other with “any.”

    First, I approach a mysterious old man. His stories are intriguing, but I can’t quite decipher their nature just from a glance. So, I use my “unknown” pouch. This pouch is special; it keeps the stories safe, but I must inspect them closely before I share them with others or weave them into my own narrative. It ensures I handle each story cautiously, taking time to understand its essence before using it.

    Next, I meet a lively merchant who eagerly hands out tales of every kind—some fascinating, others quite mundane. For these, I have my “any” pouch. It’s like a catch-all satchel, accepting any story without question. However, there’s a downside: I must be vigilant, as the stories can be unpredictable. If I share them carelessly, they might not fit well into my own tales, causing confusion or even chaos.

    As I wander the marketplace, I realize the importance of choosing the right pouch. The “unknown” pouch is my go-to when I want to delve deeper and ensure a story’s fit before sharing it. Meanwhile, the “any” pouch allows for quick collection but demands more caution when it’s time to use the gathered tales.

    So, as I continue my exploration, I learn to balance curiosity with caution, ensuring each story finds its rightful place in my collection. If this story resonated with you, feel free to share it with others who might appreciate the magic of understanding the unknown and any in our narrative quests!


    Returning to my marketplace analogy, let’s picture the “unknown” and “any” pouches as JavaScript variables, and the stories as data we want to manage. Here’s how they play out in the JavaScript world:

    // Using 'unknown'
    let unknownStory: unknown;
    unknownStory = "A tale of mystery"; // Assigning a string
    unknownStory = 42;                  // Reassigning a number
    
    // Before using unknownStory as a specific type, I need to ensure its type
    if (typeof unknownStory === "string") {
        console.log("The story is a string: " + unknownStory.toUpperCase());
    }
    
    // Using 'any'
    let anyStory: any;
    anyStory = "A tale of adventure"; // Assigning a string
    anyStory = { title: "Epic Quest" }; // Reassigning an object
    
    // I can use anyStory without type checking, but it may lead to errors
    console.log(anyStory.title); // Works, but risky if anyStory changes type

    Key Takeaways:

    1. Type Safety with unknown: Just like my “unknown” pouch, the unknown type in TypeScript requires a type check before you can perform operations on it. This ensures safety and prevents runtime errors, as I must confirm the story’s nature before telling it.
    2. Flexibility with any: The any type is like my “any” pouch, accepting any data without question. While flexible, it lacks the safety net, making it easy to introduce errors if I’m not careful about how the stories are used.
    3. Choosing the Right Tool: Use unknown when you want to enforce type checks and ensure data integrity. Opt for any when you need flexibility and are confident in handling the data with care.