myHotTake

Tag: ESLint setup

  • How to Harmonize ESLint and Prettier for Perfect Code?

    Hey there! If you enjoy this story, feel free to hit like or share it with your friends who might find it interesting.


    I’m standing in front of a giant chalkboard, a dusty piece of chalk in my hand. The task is simple yet profound—write a flawless equation that holds the room in awe. This equation is a metaphor for the perfect JavaScript code. But as I start writing, I notice two voices in my head. One whispers, “Precision!”—this is ESLint, the meticulous mathematician who demands each number and symbol be perfectly placed. The other voice chimes in with, “Flow!”—this is Prettier, the artist who wants the equation to look as beautiful as it is correct.

    I begin with ESLint, carefully drawing each element of my equation with exacting precision. The angles are sharp, and the alignment is impeccable. But as I step back, I see that while it satisfies the mathematician, the equation lacks a certain elegance, like a masterpiece without a frame.

    Then, Prettier takes the chalk. With a flourish, it smooths the edges, spacing the numbers just so, converting my rigid equation into a flowing piece of art. But wait! Some of ESLint’s rules have been overshadowed by this newfound elegance, and the mathematician within me frowns.

    I realize that for my equation to shine, these two perspectives must not just coexist but collaborate. So, I set to work, adjusting the equation with both precision and artistry in mind. I use special rules, known as ESLint-Prettier plugins, to mediate between these voices. They ensure that the mathematician’s precision and the artist’s flow work in harmony, neither overshadowing the other.

    With each stroke of chalk, I see the equation transform, each part contributing to a greater whole. Finally, as I step back, I see it—a perfect blend of precision and elegance. The equation is not just correct; it’s captivating. I feel a sense of triumph, knowing I’ve created a masterpiece that satisfies both the mathematician and the artist.


    First, I set up ESLint to catch potential errors and enforce coding standards. In my .eslintrc.json file, I define rules that ensure my code is consistent and maintainable:

    {
      "extends": ["eslint:recommended"],
      "rules": {
        "no-unused-vars": "warn",
        "eqeqeq": "error"
      }
    }

    These rules ensure that I avoid common pitfalls, like using undeclared variables or non-strict equality checks. But as I write, I remember my artist friend, Prettier, who wants my code to look just as good as it functions.

    I introduce Prettier into the mix by adding a .prettierrc configuration file:

    {
      "singleQuote": true,
      "semi": false
    }

    This setup ensures my code is formatted consistently, with single quotes and without semicolons at the end of statements, giving it that polished look.

    But here’s where the magic happens—the ESLint-Prettier plugin. I install eslint-config-prettier and eslint-plugin-prettier to ensure these tools don’t step on each other’s toes:

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

    Then, I update my ESLint configuration to include Prettier’s rules:

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

    Now, ESLint and Prettier work together seamlessly, just like the mathematician and artist in me did on the chalkboard. My code is both precise and beautiful, each tool enhancing the other’s strengths.

    Key Takeaways:

    1. ESLint and Prettier Complement Each Other: ESLint enforces coding standards and catches potential errors, while Prettier ensures consistent formatting.
    2. Configuration is Key: Use ESLint-Prettier plugins to harmonize both tools, preventing conflicts and ensuring they work in tandem.
    3. Consistent Code is King: Combining these tools leads to cleaner, more readable, and maintainable code, much like a perfectly balanced equation.
  • 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.
  • How to Automate ESLint & Prettier with Git Hooks Easily

    If you find this story twisty and fun, feel free to like and share! 🌟


    I’m standing before a colorful Rubik’s Cube, a puzzle waiting to be solved. Each twist and turn represents a step in my coding journey. I want my code to be as perfect as a completed Rubik’s Cube, with every side flawlessly aligned. That’s where ESLint and Prettier come in, my trusty companions on this quest.

    As I hold the cube, I realize that ESLint is like my guiding hand, ensuring I don’t make those awkward moves that could throw the whole puzzle off balance. It keeps me in line, whispering reminders to keep my syntax clean and errors at bay. ESLint is the patient mentor, always watching, always guiding.

    Next to ESLint is Prettier, the artist in this partnership. Prettier is like my eye for symmetry, making sure each side of the cube looks just right. It smooths out the rough edges, ensuring every color is in its place, every line of code neat and beautiful. With Prettier, my cube — my code — isn’t just functional; it’s a work of art.

    But here’s the magic: I want this duo to work even when I’m not looking. That’s where the pre-commit hook comes in. It’s like setting an automatic solver on the Rubik’s Cube. Before I snap the pieces into place and call it done, the hook leaps into action, running ESLint and Prettier. It checks my every move, ensuring I’ve not missed a beat.

    I configure this behind the scenes using a tool called Husky. Husky links my cube-solving process to a pre-commit hook. Every time I’m about to declare my puzzle complete — or my code ready to commit — Husky steps in. It runs ESLint and Prettier automatically, making sure everything aligns perfectly, just like a finished Rubik’s Cube.


    First, I needed to install the tools that would help keep my code as tidy as my cube. Using Node.js, I installed ESLint and Prettier:

    npm install eslint prettier --save-dev

    Next, I set up ESLint by creating a configuration file. This file was like the blueprint for my cube-solving strategy, detailing how I wanted ESLint to guide me:

    npx eslint --init

    This command walked me through setting up my .eslintrc.json file, where I could define rules to keep my code in check. It’s like deciding the preferred methods for solving the cube’s layers.

    With Prettier, the setup was just as simple. I added a configuration file named .prettierrc to ensure my code was consistently styled:

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

    Then came the part where I needed to ensure these tools ran automatically before each commit. This was the pre-commit hook, my secret weapon for keeping my code cube-perfect. I turned to Husky, a tool designed to help with this precisely:

    npm install husky --save-dev

    Once installed, I initialized Husky:

    npx husky install

    I created a pre-commit hook to run ESLint and Prettier using a simple command:

    npx husky add .husky/pre-commit "npx eslint . && npx prettier --write ."

    This command ensured that every time I prepared to commit my changes, ESLint would check for errors, and Prettier would format my code. It was like having an automatic cube solver ready to make the final adjustments.

    Key Takeaways:

    • ESLint and Prettier: These are essential tools for maintaining clean and consistent code. ESLint acts as the guide, catching errors, while Prettier polishes the code’s aesthetic.
    • Husky and Pre-commit Hooks: Husky automates the running of ESLint and Prettier, ensuring code quality is maintained before each commit, similar to setting an automatic solver for a Rubik’s Cube.
    • Configuration: Setting up configuration files for ESLint and Prettier is like defining the rules for cube-solving, ensuring consistency and adherence to best practices.
  • 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 Enforce Coding Standards in TypeScript Projects?

    Hey there! If you enjoy this story, feel free to give it a like or share it with others who might find it interesting.


    I’m leading a band of explorers on an adventure through the dense, jungle that is our TypeScript project. Each member of my team is an expert in their own right, but without a clear path and some rules to guide us, chaos can quickly ensue. To make sure we all stay on track and avoid getting lost in the thicket, I decide to enforce some ground rules—these are our coding standards.

    Think of these coding standards as a compass. Just like a compass helps us navigate through the jungle by pointing us in the right direction, coding standards guide us in writing consistent and reliable code. This compass ensures that even if we encounter unexpected challenges or complex coding problems, we all approach them using a common language and understanding.

    Now, to make sure everyone has a compass in hand, I use tools like ESLint and Prettier. These are like the rugged, trusty gadgets in our explorer kit; they check our work and ensure we’re following the path. ESLint is like our map reader, pointing out when we stray from the path with warnings and errors. Prettier, on the other hand, is like our tidy camp leader, making sure everything looks neat and organized, so we can quickly find what we need.

    I also set up a campfire meeting—our code reviews. Around this campfire, we gather to discuss our journey, share insights, and ensure everyone is aligned. It’s here that we reinforce our rules and help each other improve. This camaraderie makes our group stronger and our journey smoother.

    Finally, I establish a base camp—a Continuous Integration system. This base camp is our checkpoint, where code is automatically tested and validated before it’s allowed to proceed further. It acts as a safeguard, ensuring that any deviation from our standards is caught early, preventing us from venturing into dangerous territory.

    In this way, by using a compass, gadgets, campfire meetings, and a base camp, I ensure our TypeScript project stays on course, with everyone working together harmoniously, like a well-oiled expedition team. And that’s how I enforce coding standards on our adventurous journey through the TypeScript jungle.


    The Compass: Coding Standards

    The coding standards are like our compass, guiding us through the wilds of JavaScript. For example, we might have a rule that all functions should use arrow function syntax for consistency:

    // Bad: Regular function declaration
    function add(a, b) {
        return a + b;
    }
    
    // Good: Arrow function
    const add = (a, b) => a + b;

    The Gadgets: ESLint and Prettier

    ESLint acts as our map reader, pointing out deviations. Here’s an example of an ESLint rule that enforces the use of === instead of ==:

    // ESLint configuration
    {
      "rules": {
        "eqeqeq": "error"
      }
    }
    
    // Bad: Using ==
    if (a == b) {
      // ...
    }
    
    // Good: Using ===
    if (a === b) {
      // ...
    }

    Prettier, our tidy camp leader, ensures our code is formatted consistently. It might automatically reformat code like this:

    // Before Prettier
    const multiply=(a,b)=>{return a*b;}
    
    // After Prettier
    const multiply = (a, b) => {
      return a * b;
    };

    The Campfire: Code Reviews

    Our campfire meetings—code reviews—are where we reinforce our standards. During a review, I might suggest improvements like using destructuring for cleaner code:

    // Original code
    const user = getUser();
    const name = user.name;
    const age = user.age;
    
    // Improved with destructuring
    const { name, age } = getUser();

    The Base Camp: Continuous Integration

    Our base camp, or Continuous Integration (CI) system, automatically runs tests and linting checks. Here’s an example of a simple CI configuration using GitHub Actions:

    name: CI
    
    on: [push]
    
    jobs:
      build:
        runs-on: ubuntu-latest
    
        steps:
        - uses: actions/checkout@v2
        - name: Install dependencies
          run: npm install
        - name: Run ESLint
          run: npm run lint
        - name: Run tests
          run: npm test

    Key Takeaways

    1. Consistency is Key: Establishing coding standards ensures that all team members write code in a consistent manner, making it easier to read and maintain.
    2. Automate with Tools: Use tools like ESLint and Prettier to automate the enforcement of these standards, reducing manual errors and improving productivity.
    3. Collaborate and Learn: Code reviews are invaluable for sharing knowledge and improving code quality.
    4. Safeguard with CI: Implement a Continuous Integration system to automatically verify code changes, catching issues early in the development process.
  • 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.