myHotTake

Tag: ESLint guide

  • How to Build a JavaScript Monorepo with Babel, ESLint & Webpack

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


    I’m embarking on an ambitious project: building a skyscraper. The skyline awaits my creation, and I know that to succeed, I need the perfect blend of tools, much like how I approach setting up a monorepo with Babel, ESLint, and Webpack.

    First, I envision Babel as my architectural blueprint. Just as blueprints translate the architect’s vision into detailed plans that workers can understand, Babel transforms cutting-edge JavaScript into code that any browser can execute. With Babel, I ensure that my skyscraper—my code—stands tall and accessible, no matter the browser’s age or capability.

    Next, I bring in ESLint, my diligent site inspector. Like an inspector meticulously checking every beam and bolt, ESLint scans through my code, ensuring it adheres to the highest standards. It catches potential flaws, ensuring that the structure is not only impressive but also stable and safe. With ESLint, I can confidently say that my skyscraper meets all the necessary regulations and is devoid of errors that might cause future problems.

    Finally, I turn to Webpack, my project’s construction manager. Just as a manager coordinates various teams to ensure the skyscraper rises seamlessly, Webpack bundles all my code into a cohesive unit. It optimizes resources, manages dependencies, and ensures that each component of my skyscraper fits perfectly together. With Webpack, the complex array of features and functionalities are streamlined, resulting in a polished and efficient structure.


    Step 1: Setting Up the Monorepo

    First, I create my foundational monorepo structure, akin to laying down the skyscraper’s base. I start by initializing a new npm project.

    mkdir my-skyscraper
    cd my-skyscraper
    npm init -y

    I then add a packages directory where different parts of my project will reside, similar to different floors of a skyscraper.

    mkdir packages

    Step 2: Configuring Babel

    Just like crafting detailed architectural blueprints, I set up Babel to ensure my code is universally understood.

    npm install --save-dev @babel/core @babel/preset-env

    I create a Babel configuration file that serves as my blueprint:

    // babel.config.json
    {
      "presets": ["@babel/preset-env"]
    }

    Step 3: Integrating ESLint

    Next, I bring in ESLint to ensure everything is built to code. It’s like having my inspector ensure every part of the project meets quality standards.

    npm install --save-dev eslint
    npx eslint --init

    I configure ESLint in a .eslintrc.json file, setting rules to keep my project in top shape:

    // .eslintrc.json
    {
      "env": {
        "browser": true,
        "es2021": true
      },
      "extends": "eslint:recommended",
      "parserOptions": {
        "ecmaVersion": 12
      },
      "rules": {
        "indent": ["error", 2],
        "quotes": ["error", "double"]
      }
    }

    Step 4: Setting Up Webpack

    Finally, I configure Webpack, my construction manager, to bundle everything efficiently.

    npm install --save-dev webpack webpack-cli

    I create a webpack.config.js file to manage all components:

    // webpack.config.js
    const path = require('path');
    
    module.exports = {
      entry: './packages/main/index.js',
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
      },
      module: {
        rules: [
          {
            test: /\.m?js$/,
            exclude: /node_modules/,
            use: {
              loader: 'babel-loader',
            },
          },
        ],
      },
    };

    Final Thoughts

    With this setup, I’ve constructed a robust foundation for my JavaScript project, much like erecting a skyscraper with each tool playing a pivotal role. Babel ensures compatibility, ESLint guarantees quality, and Webpack orchestrates everything into a seamless structure.

    Key Takeaways:

    1. Babel acts as the blueprint, converting modern JavaScript for all environments.
    2. ESLint serves as the inspector, maintaining code quality and adherence to best practices.
    3. Webpack is the construction manager, bundling and optimizing the project efficiently.
  • How to Design Custom ESLint Rules: A Colorful Guide

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


    I decided to design a logo with bold colors for a new brand. As I sat in my studio, surrounded by swatches and creative chaos, I realized that creating a custom ESLint rule for a JavaScript project was quite similar to this colorful endeavor.

    I envisioned the logo as the project itself—unique, tailored, and bursting with personality. To craft this distinctive emblem, I needed to set some guidelines, much like I would with an ESLint rule. So, I began by defining the “rules” of my design: I wanted the colors to be bold and harmonious, capturing the essence of the brand.

    First, I picked up my brush, equivalent to setting up a new JavaScript file, and started sketching the core shapes—the basic structure of my rule. I knew I wanted my rule to ensure that the project’s code followed a specific pattern, just as I wanted my logo to follow a specific aesthetic.

    Next, I mixed the paints, choosing the right shades to bring my vision to life. This was akin to using ESLint’s Abstract Syntax Tree (AST) to analyze the code. I defined the conditions and exceptions, just as I blended colors to find the perfect balance. As I painted, I constantly checked the harmony of the colors, ensuring they worked together seamlessly, much like testing my rule against various code snippets to ensure it functioned correctly.

    As the logo took shape, I refined the details—adding shadows here, a splash of color there—fine-tuning my creation. Similarly, I tweaked my ESLint rule, adjusting the logic and adding helpful error messages to guide developers, just as my logo would guide the viewer’s eye.

    Finally, I stood back, admiring my work: a bold, beautiful logo that spoke volumes with its colors. In the same way, my custom ESLint rule was now a part of the project’s toolkit, ensuring code quality and consistency with every stroke of the keyboard.


    First, I started by creating a new directory in my project for ESLint rules, much like setting up a fresh canvas. Inside, I added a new file, no-bold-colors.js, to house my rule. This rule would be like a guideline for developers, ensuring they avoided using inline styles with bold colors directly in JSX.

    // no-bold-colors.js
    module.exports = {
      meta: {
        type: 'suggestion',
        docs: {
          description: 'disallow inline styles with bold colors',
          category: 'Stylistic Issues',
          recommended: false,
        },
        messages: {
          noBoldColors: 'Avoid using bold colors directly in inline styles.',
        },
        schema: [], // no options
      },
      create(context) {
        return {
          JSXAttribute(node) {
            if (
              node.name.name === 'style' &&
              node.value &&
              node.value.expression &&
              node.value.expression.properties
            ) {
              node.value.expression.properties.forEach((property) => {
                if (
                  property.key.name === 'color' &&
                  ['red', 'blue', 'green'].includes(property.value.value)
                ) {
                  context.report({
                    node,
                    messageId: 'noBoldColors',
                  });
                }
              });
            }
          },
        };
      },
    };

    In this code, much like mixing the right shades for my logo, I specified a rule that would trigger a warning whenever inline styles with bold colors were detected.

    Next, I configured ESLint to recognize my custom rule. I added a new plugin reference in my ESLint configuration file, telling the system where to find my masterpiece.

    // .eslintrc.js
    module.exports = {
      plugins: ['my-custom-rules'],
      rules: {
        'my-custom-rules/no-bold-colors': 'warn',
      },
    };

    Just as the logo’s bold colors needed to be in harmony, this setup ensured my rule was part of the project’s stylistic guidelines, maintaining the integrity of the codebase.

    As developers worked, much like artists at their easels, the rule provided gentle reminders to steer clear of undesirable patterns. It enforced consistency and quality, just as my logo represented the brand’s vision.

    Key Takeaways/Final Thoughts:
    Creating a custom ESLint rule is like designing a logo with bold colors: it requires creativity, precision, and careful planning. By setting up a custom rule, you ensure code quality and maintainability, much like how a well-designed logo ensures brand consistency. Don’t be afraid to mix and match, experiment, and refine your rules—each line of code is a stroke towards a more and cohesive project.

  • Why Is Code Linting Crucial for JavaScript Developers?

    Hey there! If you enjoy this story and find it helpful, please give it a like or share it with others who might appreciate a little JavaScript wisdom.


    I’m out in the woods, trying to build the perfect campfire. It’s late, and the chill in the air makes it a necessity. My goal? Create a warm, inviting blaze that doesn’t just flicker out after a few minutes. I start by gathering all the materials I need: dry wood, some kindling, and a match. But as I lay the wood down, I notice it’s all jumbled up, with some pieces too big and others too small. If I light it as is, it’ll likely struggle to catch fire properly. This is where my trusty guide, let’s call it “Campfire Linting,” comes into play.

    Campfire Linting is like having an expert camper by my side, gently nudging me to rearrange the wood into a neat, structured pile. It points out that the twigs need to be at the bottom, with gradually larger pieces on top, ensuring a steady and efficient burn. It’s not that I don’t know how to build a fire, but having this guidance helps me avoid mistakes and makes the whole process smoother.

    In the world of JavaScript, code linting is my Campfire Linting. It’s a tool that reviews my code, pointing out errors, inconsistencies, and suggesting improvements. Just like a poorly arranged campfire might struggle or smoke excessively, messy code can cause bugs and performance issues. Code linting helps me spot potential problems early on, ensuring my code is clean, efficient, and ready to run smoothly.


    I’m writing a simple JavaScript function to calculate the area of a rectangle. Here’s the first draft of my code:

    function calculateArea(length, width) {
        area = length * width
        return area
    }

    At first glance, this might seem fine. But just as a campfire needs careful arrangement to burn efficiently, my code needs a bit of tidying up. This is where a linter like ESLint comes in. It would point out a few issues:

    1. Missing var, let, or const: My variable area is undefined in strict mode, which could lead to unexpected behavior.
    2. Missing semicolon: Although JavaScript is forgiving with semicolons, it’s best practice to include them for clarity and consistency.

    With the linting suggestions in mind, I refine my code:

    function calculateArea(length, width) {
        const area = length * width;
        return area;
    }

    Now, my code is clean, following best practices, and free of potential pitfalls. Just as my carefully arranged campfire burns steadily, this well-structured code will execute reliably.

    Key Takeaways:

    • Code linting is like having a guide to ensure your JavaScript code is clean, efficient, and free of errors.
    • Best practices such as defining variables properly and using semicolons can prevent issues and improve readability.
    • Tools like ESLint can automatically check your code, pointing out mistakes and suggesting improvements, much like a seasoned camper advising on fire-building techniques.
    • Embracing linting tools not only helps avoid bugs but also encourages learning and adopting better coding habits.
  • How Do ESLint and Prettier Polish Your JavaScript Code?

    If you enjoy this story and find it helpful, feel free to like or share it with others who might appreciate a good tale about JavaScript!


    I’m standing in a workshop, staring at a rough piece of wood. This wood is like my JavaScript code—full of potential but in need of some serious refining. I have two trusty tools at my side: a wise old craftsman named ESLint and a smooth-talking artisan named Prettier. Both are eager to help me transform this rough block into a masterpiece.

    I pick up ESLint first. He’s like a seasoned mentor, pointing out every flaw in my wood. “See that notch? That’s going to be a problem later,” he says, tapping his finger on a splinter. ESLint is all about the structure. He highlights where my wood might crack or where the grain isn’t quite right. He ensures that every joint will fit perfectly, and that the foundation of my piece is solid. His attention to detail is impeccable, ensuring that the integrity of my final product is flawless.

    Then, I turn to Prettier. With a flourish, he begins to sand away the rough edges. Unlike ESLint, Prettier isn’t concerned with the structural integrity; he’s focused on the surface. He makes the wood shine, smoothing out the surface until it’s pleasing to both the eye and the touch. With Prettier, the wood becomes something beautiful, with every edge softened and every surface gleaming.

    As I work, I realize that both ESLint and Prettier are essential. ESLint helps me ensure that my piece won’t fall apart—that it’s functional and robust. Prettier, on the other hand, makes sure it looks good, that it’s polished and elegant.


    First, I call upon ESLint. I run it against my codebase, and it immediately starts pointing out issues. For instance, let’s say I have this piece of code:

    const greet = (name) => {
        console.log("Hello, " + name)
    }
    
    greet('Alice')

    ESLint steps in and says, “Hold on! There’s a missing semicolon at the end of the console.log statement.” It also suggests using template literals for cleaner string concatenation. With ESLint’s guidance, I make the changes:

    const greet = (name) => {
        console.log(`Hello, ${name}`);
    }
    
    greet('Alice');

    My code is now structurally sound, thanks to ESLint’s keen eye for detail.

    Next, I bring Prettier into the mix. Prettier isn’t concerned with the logic or semantics of my code; instead, it focuses on its appearance. It takes care of inconsistent spacing, line breaks, and other formatting issues. This makes my code more readable and consistent. With Prettier, even if I have a long function that’s a bit messy, like this:

    function calculateSum(a, b) {
        let sum = a+b; return sum;
    }

    Prettier will automatically reformat it to look neat and tidy:

    function calculateSum(a, b) {
      let sum = a + b;
      return sum;
    }

    With both ESLint and Prettier at work, my code is not only correct but also easy on the eyes. ESLint ensures that my code follows best practices and is free of errors, while Prettier makes it visually clean and consistent.


    Key Takeaways:

    1. ESLint is like the craftsman who ensures your code is structurally sound, catching errors and enforcing coding standards.
    2. Prettier is the artisan who polishes your code, making it look consistent and aesthetically pleasing without changing its functionality.
    3. Using both tools together creates a codebase that is both robust and easy to read, much like a well-crafted piece of wood that is both sturdy and beautiful.
  • How Do Linters and Formatters Enhance JavaScript Code?

    Hey there! If you enjoy this story, feel free to give it a like or share it with someone who loves building websites too!

    I’m building a website which is honestly like constructing a house. Each line of JavaScript code is a brick that fits into the larger structure. As I lay each brick, I want to make sure they are aligned perfectly, with no cracks or weak spots that could cause the structure to crumble. This is where my trusty helpers, the linters and formatters, come into play.

    First, let me introduce you to my friend, Linty the Linter. Linty is like a meticulous inspector, always walking around my construction site with a magnifying glass in hand. Linty has a keen eye for spotting any issues with my bricks—perhaps one is slightly crooked, or maybe there’s a small crack. These are the bugs and errors in my code. Linty gives me a nudge and says, “Hey, this brick isn’t quite right. You might want to fix that before moving on.” Thanks to Linty, my website remains sturdy and reliable.

    Then there’s Formy the Formatter, my other indispensable ally. Formy is like an artist who ensures that every brick is not only solid but also aesthetically pleasing. With a paintbrush in hand, Formy goes over the bricks, making sure they’re all the same color, size, and shape, and that they align beautifully with one another. This is the art of keeping my code clean and readable. With Formy by my side, the walls of my website are not just functional, but also a joy to look at.


    As I continue building my website, I realize that Linty, my linter, works through tools like ESLint. I’m writing some JavaScript code to handle user input:

    function processInput(userInput) {
      if(userInput == "hello") {
        console.log("Hi there!");
      }
    }

    Linty takes a closer look and says, “Hey, there’s something off here. You’re using == instead of ===. That could lead to unexpected results!” By pointing out this potential issue, Linty helps me avoid bugs before they even have a chance to disrupt my website.

    So, I tweak the code:

    function processInput(userInput) {
      if(userInput === "hello") {
        console.log("Hi there!");
      }
    }

    Now, onto Formy, the formatter. Suppose my code started out like this, with inconsistent spacing:

    function processInput(userInput){if(userInput==="hello"){console.log("Hi there!");}}

    Formy, using tools like Prettier, sweeps in with a flourish and rearranges it into a more readable and consistent format:

    function processInput(userInput) {
      if (userInput === "hello") {
        console.log("Hi there!");
      }
    }

    With Formy’s touch, my code is not only functional but also easy to read, making future updates and debugging much simpler.

    Key Takeaways:

    1. Linters like ESLint are crucial for catching potential errors and enforcing coding best practices, acting like a vigilant inspector for your code.
    2. Formatters like Prettier ensure your code is consistently styled and easy to read, much like an artist beautifying the construction.
    3. Together, linters and formatters maintain the robustness and elegance of your JavaScript projects, ensuring each line of code is as reliable and attractive as the bricks in a well-built wall.