myHotTake

Tag: JavaScript linting

  • 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.

  • How to Seamlessly Integrate ESLint & Prettier in CI/CD?

    Hey there! If you enjoy this little tale and find it helpful, feel free to like or share it with your fellow code adventurers.


    Once upon a time, in the kingdom of Codebase, I was a brave developer tasked with maintaining the peace and harmony of our beloved application. Every day, I faced the relentless horde of bugs and errors that threatened to bring chaos to our realm.

    One fateful day, I discovered two powerful allies—ESLint and Prettier. Like a wise sage and a meticulous craftsman, they promised to help me keep my code clean and error-free. But how could I ensure their magic worked every time I deployed my creations to production? The answer lay in the mystical land of CI/CD pipelines.

    I began my quest by configuring ESLint to enforce the kingdom’s coding standards. With a few lines of configuration, I enlisted its watchful eye to scan my JavaScript code for any lurking mistakes or inconsistencies. ESLint was like a seasoned detective, always on the lookout for the tiniest of errors that could disrupt the harmony.

    Next, I sought the assistance of Prettier, the artisan of formatting. With a simple touch, Prettier transformed my code into a masterpiece, ensuring every line was beautifully aligned and easy to read. It was like watching a skilled artist meticulously crafting a work of art, where every stroke mattered.

    With my trusted companions by my side, I ventured into the CI/CD pipeline, a assembly line that automated the process of building, testing, and deploying my code. I integrated ESLint and Prettier into this enchanted pipeline, ensuring that each pull request was scrutinized and polished before it could reach the sacred production environment.

    The pipeline became my loyal sentinel, ceaselessly running ESLint to catch any new errors and invoking Prettier to maintain the elegance of my code. It was like having an ever-vigilant guardian, tirelessly working to keep my kingdom free from the chaos of bugs.


    To begin, I needed to set up ESLint in my project. I opened my terminal and initiated the ESLint configuration wizard:

    npx eslint --init

    I answered the prompts, selecting my preferred settings, and soon, a .eslintrc.json file appeared in my project. This file was like a spellbook, containing rules that ESLint would follow to keep my code in check.

    Here’s a peek at what my .eslintrc.json looked like:

    {
      "env": {
        "browser": true,
        "es2021": true
      },
      "extends": "eslint:recommended",
      "parserOptions": {
        "ecmaVersion": 12,
        "sourceType": "module"
      },
      "rules": {
        "no-unused-vars": "warn",
        "eqeqeq": "error"
      }
    }

    With ESLint set up, it was time to introduce Prettier. I installed it into my project:

    npm install --save-dev prettier

    Then, I created a .prettierrc file to define Prettier’s formatting rules:

    {
      "singleQuote": true,
      "trailingComma": "es5"
    }

    To ensure ESLint and Prettier worked harmoniously, I added the eslint-config-prettier package to disable any ESLint rules that might conflict with Prettier’s formatting:

    npm install --save-dev eslint-config-prettier

    I updated my .eslintrc.json to include this configuration:

    {
      "extends": [
        "eslint:recommended",
        "plugin:prettier/recommended"
      ]
    }

    With the setup complete, I wrote a simple JavaScript function to test my newfound tools:

    function greet(name) {
      if (name == 'World') {
        console.log('Hello, ' + name + '!');
      }
    }
    
    greet('World');

    Running ESLint on this code:

    npx eslint myfile.js

    ESLint pointed out that I should use === instead of ==. I corrected the code:

    function greet(name) {
      if (name === 'World') {
        console.log('Hello, ' + name + '!');
      }
    }

    Next, I let Prettier work its formatting magic:

    npx prettier --write myfile.js

    The result was a beautifully formatted and error-free piece of code, ready for deployment.

    Key Takeaways:

    1. Setup and Configuration: ESLint and Prettier can be easily integrated into a JavaScript project with a few configuration steps, ensuring code quality and consistency.
    2. CI/CD Integration: By incorporating these tools into a CI/CD pipeline, I can automate code checks before deployment, reducing errors in production.
    3. Harmony in Tools: Using eslint-config-prettier helps avoid conflicts between ESLint rules and Prettier’s formatting, ensuring a smooth workflow.
    4. Continuous Learning: Whether through stories or code, continuously exploring new tools and practices can greatly enhance the quality of my work as a developer.
  • How Does ESLint Enhance Your JavaScript Coding Journey?

    Hey there! If you find this story helpful or enjoyable, feel free to give it a like or share it.


    I’ve just bought a shiny new computer (bye bye paycheque). It’s sleek, fast, and ready to handle anything I throw at it. But before I start using it, I need to install some essential software to ensure it runs smoothly and efficiently. This is exactly what setting up ESLint in a new JavaScript project feels like.

    I begin by unboxing my new computer, which represents creating a new JavaScript project. It’s fresh, untouched, and full of potential. But to make sure my coding experience is seamless, I need to install ESLint, just like I’d install an operating system or antivirus software on my computer.

    To get started, I open up my terminal, the command center of my coding universe. I type in npm init -y, which is like initializing the setup process for my new project, much like setting up a user account on my new computer. With the initial setup done, I proceed to install ESLint by typing npm install eslint --save-dev. This step is akin to downloading that essential software that will keep my computer safe and optimized.

    Once ESLint is installed, I need to configure it, just as I would personalize the settings on my new machine. I run npx eslint --init, and ESLint starts asking me questions about my preferences. Do I want to use popular style guides like Airbnb or Google? Or perhaps I want to define my own rules, much like choosing between a pre-set desktop theme or customizing my own. This configuration ensures ESLint is tailored to my project’s needs, just like how I’d configure software to suit my workflow.

    As I finish setting up ESLint, I feel a sense of accomplishment, similar to the satisfaction of knowing my computer is running at its best. With ESLint in place, my coding environment is now equipped to catch pesky errors and enforce consistent code style, making sure my project runs as smoothly as a well-oiled machine.


    I start by writing a simple function in my app.js file:

    function greet(name) {
        console.log("Hello, " + name + "!");
    }

    As I type, ESLint acts like a vigilant guide, immediately pointing out that I forgot to use semicolons. It’s like having an alert system on my computer, reminding me to save my work or update my software. I quickly correct it:

    function greet(name) {
        console.log("Hello, " + name + "!");
    }

    Next, I decide to enhance my function using ES6 features. I refactor it to use template literals, making it more modern and clean:

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

    ESLint gives me a nod of approval, indicating that my code now adheres to the best practices. It’s similar to getting that reassuring notification that my antivirus is up-to-date and my computer is secure.

    But wait, there’s more! As I continue coding, I write a piece of code that looks like this:

    let unusedVariable = 42;
    console.log("Welcome to the JavaScript world!");

    ESLint alerts me about the unused variable, much like a helpful nudge to clean up unnecessary files on my computer. I quickly remove it:

    console.log("Welcome to the JavaScript world!");

    With ESLint’s guidance, my code is cleaner, more efficient, and free of potential pitfalls. This experience is akin to maintaining a well-organized desktop, where everything is in its place and easy to find.

    Key Takeaways/Final Thoughts:

    1. Consistency and Best Practices: ESLint ensures that my JavaScript code is consistent and follows best practices, much like having an organized file system on my computer.
    2. Error Prevention: With ESLint, I catch errors early, preventing bugs down the road, similar to how antivirus software catches potential threats before they cause harm.
    3. Code Quality: By adhering to ESLint’s rules, my code quality improves, just like keeping my computer’s software updated leads to better performance.
    4. Customizable Experience: Just as I can customize my computer’s settings, ESLint allows me to tailor its configuration to suit my project’s needs.
  • What is a .eslintrc File? Discover Its Role in JavaScript!

    Hey there! If you find this story as enchanting as weaving a tapestry, feel free to like or share it with fellow artisans of code.


    I am a travelling weaver, setting out to create a tapestry with intricate patterns. Each thread must be perfectly aligned, every color in harmony, and the design must be flawless. To ensure this masterpiece unfolds without a hitch, I have a scroll—my .eslintrc file.

    This scroll is like a guide, whispered in the language of JavaScript, dictating the rules for how each thread should behave. I picture it as the wise overseer, ensuring no threads go astray, no colors clash, and no patterns diverge from the design. It lays out the principles I must follow: “Use this stitch here,” it says, “avoid that knot there.”

    As I weave, the scroll’s enchantments alert me whenever a thread threatens to stray from the intended path, gently reminding me to adjust my technique to maintain the tapestry’s beauty. It’s like having an ever-watchful mentor by my side, ensuring that my creation remains true to its vision.

    Without this guide, my tapestry could become a tangled mess of rogue threads and chaotic patterns. But with it, my work flourishes, each section of the tapestry a testament to the harmony and precision that the scroll brings.


    Here’s how I set up this scroll:

    {
      "env": {
        "browser": true,
        "es2021": true
      },
      "extends": "eslint:recommended",
      "parserOptions": {
        "ecmaVersion": 12,
        "sourceType": "module"
      },
      "rules": {
        "indent": ["error", 2],
        "quotes": ["error", "double"],
        "semi": ["error", "always"],
        "no-console": "warn"
      }
    }

    In this script, I define the environment (env) where my tapestry will be displayed, ensuring that my code is compatible with the latest standards. The extends property acts like a foundation, borrowing knowledge from experienced weavers who’ve come before me, setting a baseline of best practices.

    The parserOptions determine the dialect of JavaScript I’m using, ensuring that my loom is set up to understand the latest techniques and styles. Meanwhile, the rules section is where the true magic happens. Here, I specify that each indentation must be two spaces, akin to keeping each thread equally spaced. I require double quotes for strings, ensuring uniformity, much like a consistent color scheme in my tapestry. Semicolons? They must always be present, like the knots that secure my threads.

    And when a console log threatens to disrupt the harmony of my work, a gentle warning nudges me back on track, reminding me to keep the tapestry clean and professional.

    Key Takeaways:

    • The .eslintrc file is crucial for maintaining consistent and error-free JavaScript code.
    • It provides a structured environment for your code, much like a well-organized loom for weaving.
    • By defining rules and configurations, it helps prevent common mistakes and ensures your code adheres to a set of best practices.
    • Think of it as a customizable guide that adapts to your personal weaving style, helping you craft your JavaScript creations with precision and elegance.
  • How to Seamlessly Integrate Linting and Testing in JavaScript?

    Hey there, if you find this story enjoyable, feel free to like or share it with others who might appreciate a creative twist on coding concepts!


    I’m an artist setting up my digital painting studio on a sleek tablet. Before I can dive into the world of colors and brush strokes, I need to ensure my workspace is tidy and my tools are in perfect order. This is where my trusty code linting and unit tests come into play.

    I start by opening my digital canvas, just as I would initialize my coding environment. Here, my code linting tool is like a vigilant assistant, constantly scanning my brushes and color palette to ensure everything is in place and nothing is smudged or out of order. It’s like having an art critic who checks if my colors are clashing or if my lines are wonky before I even begin painting. This early check helps me prevent any glaring mistakes, much like catching syntax errors or style issues before running my code.

    With my workspace immaculate, I transition to sketching the outline of my painting. This is akin to writing my first set of unit tests. Each stroke needs precision, and my unit tests are there to confirm that every line contributes to the overall masterpiece. They reassure me that if I add a splash of color, it won’t distort the whole image. These tests are the foundations that hold my painting together, verifying that each element aligns with my vision.

    Now, as I blend colors and add layers, I continuously switch back and forth between the linting checks and unit tests. It’s a dynamic process, much like an assembly line where everything flows seamlessly. If a brush stroke seems off, my linting assistant alerts me, allowing me to correct it immediately. Meanwhile, my unit tests ensure that each addition enhances rather than detracts from the final piece.


    I’m working on a JavaScript project. The first step, akin to preparing my digital canvas, is setting up a linter like ESLint. Here’s how I might do it:

    # Initialize a new Node.js project
    npm init -y
    
    # Install ESLint
    npm install eslint --save-dev
    
    # Initialize ESLint configuration
    npx eslint --init

    With ESLint configured, my code linting assistant is ready to catch errors and enforce style guidelines. It’s like having a guide that whispers, “Hey, that variable name could be clearer,” or “Watch out, that function might not work as expected.”

    Next, I move on to writing unit tests, much like sketching the outline of my painting. For this, I use a test framework like Jest:

    # Install Jest
    npm install jest --save-dev
    
    # Create a simple function and a test

    For instance, let’s say I have a function that adds two numbers:

    // add.js
    function add(a, b) {
      return a + b;
    }
    module.exports = add;

    And a corresponding test:

    // add.test.js
    const add = require('./add');
    
    test('adds 1 + 2 to equal 3', () => {
      expect(add(1, 2)).toBe(3);
    });

    With the test in place, I can run Jest to ensure my function performs as expected:

    # Run tests
    npx jest

    As I iterate on my code, ESLint and Jest work in tandem, just like my assistant and unit tests during the painting process. If I make a mistake or deviate from best practices, ESLint guides me back on track, while Jest confirms that my functions behave correctly.

    Key Takeaways:

    1. Set Up a Strong Foundation: Just as a clean workspace is essential for art, a well-configured development environment with tools like ESLint and Jest is crucial for coding.
    2. Continuous Feedback Loop: Integrating linting and tests provides continuous feedback, ensuring that code quality and functionality are maintained throughout development.
    3. Catch Errors Early: Linting helps catch syntax errors and enforce style guidelines early in the process, preventing larger issues down the line.
    4. Ensure Code Functionality: Unit tests validate that each piece of code works as intended, safeguarding against bugs when code changes.
  • How to Seamlessly Migrate JavaScript to TypeScript

    If you find this story helpful, feel free to like or share it with others who might appreciate a little tech tale.


    I’m a ship captain setting sail on an ocean, transitioning from familiar waters to more challenging seas. This journey represents migrating from JavaScript to TypeScript. As a captain, I want my ship to be shipshape and Bristol fashion. This means I need to ensure the rigging is tight and the sails are set perfectly. This is where linting and formatting come into play.

    Linting is like having a trusty deckhand who spots potential issues with the ship’s rigging before they become problems. As we sail through the sea of code, my deckhand alerts me if a line is frayed or a knot is loose, ensuring everything is secure and up to standard. In TypeScript, setting up a linter like ESLint helps me catch errors and maintain code quality, preventing our ship from veering off course.

    On the other hand, formatting is akin to the precise way I arrange the sails for maximum efficiency. Just as a well-set sail catches the wind perfectly, proper code formatting ensures our ship runs smoothly and efficiently. By using a tool like Prettier, I can ensure that my code is consistently structured, making it easier for my crew to navigate and work together harmoniously.

    As I embark on this migration journey, I set up my linting and formatting tools as my essential navigational instruments. They guide me, ensuring that our transition to TypeScript is seamless and that our ship remains on the right course, no matter how turbulent the seas ahead. And so, with my trusty deckhand and perfectly arranged sails, I’m ready to conquer the new TypeScript waters.


    Linting with ESLint

    my deckhand, ESLint, diligently inspecting our ship. Here’s how it might look in code:

    First, we install ESLint:

    npm install eslint --save-dev

    Then, we set it up with a configuration file, .eslintrc.js:

    module.exports = {
      parser: '@typescript-eslint/parser', // Specifies the ESLint parser for TypeScript
      extends: [
        'eslint:recommended', // Use recommended rules
        'plugin:@typescript-eslint/recommended', // Use recommended TypeScript rules
      ],
      rules: {
        // Custom rules go here
        'no-console': 'warn', // Warn when console statements are used
      },
    };

    In this setup, ESLint helps us maintain our ship’s integrity by warning us about, say, stray console.log statements that might clutter our code.

    Formatting with Prettier

    Next, we ensure our sails are perfectly arranged with Prettier:

    First, install Prettier:

    npm install prettier --save-dev

    Then, create a configuration file, .prettierrc:

    {
      "semi": true, // Use semicolons at the end of statements
      "singleQuote": true, // Use single quotes instead of double
      "trailingComma": "es5" // Add trailing commas where valid in ES5
    }

    With Prettier, our code is consistently formatted, making it easier for any crew member to read and work on.

    Key Takeaways

    1. Consistency and Quality: Linting and formatting tools like ESLint and Prettier ensure that our codebase remains consistent and of high quality, making it easier to manage and less prone to errors.
    2. Seamless Transition: These tools make the migration from JavaScript to TypeScript smoother, catching potential issues early and ensuring our code adheres to best practices.
    3. Team Collaboration: A clean and consistent codebase is easier for the team to navigate, reducing misunderstandings and increasing productivity.