Setting up lint-staged for Vue projects: A step-by-step guide

After setting up a new Vue3 app using the Vue CLI and configuring Prettier as my linter, I decided to implement commitlint, husky, and lint-staged for validating commit messages and linting the code before pushing it.

My Approach

Following the instructions at , I configured commitlint with husky by running the commands:

npm install --save-dev @commitlint/{cli,config-conventional}
echo "module.exports = { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js

npm install husky --save-dev
npx husky install
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit $1'

Next, based on the guidelines at https://github.com/okonet/lint-staged#installation-and-setup, I set up lint-staged with the following command:

npx mrm@2 lint-staged

Then, within the package.json file, I replaced the existing lint-staged configuration with:

"lint-staged": {
  "*": "npm run lint"
}

The Issue

Upon modifying the README.md file in the project and attempting to commit the changes, an error message was encountered:

[... Error message details ...]

Desired Outcome

I aim to only fix files that have been modified, ensuring that the linter focuses on "lintable" files (js, ts, vue, html, etc.). The goal is to avoid errors when utilizing lint-staged with the setup configuration of

"*": "npm run lint"
.

What is the correct approach for configuring lint-staged to target "lintable" files exclusively?

Answer №1

Update on comments concerning lint-staged syntaxes

Different options for lint-staged syntax

I proposed the use of

"**/*.{js,vue}": ["npm run lint:js:fix"]
. Keep in mind that the choice of lint:js:fix is subjective and can be customized to your preferences. It follows the naming convention used by Kent C Dodds, but you could opt for something like lint:watermelon-potato-hehe if you prefer.

In terms of your suggestions:

  1. "**/*.{vue,js,jsx,ts,tsx}": "npm run lint"
    , this configuration covers a wider range of extensions, which is perfectly okay. While .tsx/.jsx may not be commonly used among Vue developers, incorporating .ts might require additional plugins in your ESlint setup. Personally, I recommend checking out tools like Vitesse for starting a Vue3 project with TypeScript support.

Regarding the second part, I generally prefer setting up my own ESlint configuration using eslint --ext .js,.vue --fix. This way, I have more control over the process and better visibility into any troubleshooting that might be required. While tools like vue-cli-service lint offer default configurations tailored for Vue projects, I lean towards creating a personalized Vue configuration alongside vanilla ESlint for a more tailored approach.

If speed is your priority, utilizing vue-cli-service lint for quick linting can be helpful. However, for a more precise configuration and smoother workflow, opting for vanilla ESlint provides greater flexibility and control, potentially reducing issues in the long run.

  1. "**/*.{vue,js,jsx,ts,tsx}": "eslint --ext .vue,.js,.jsx,.ts,.tsx --fix"
    . Although both sides contain similar scripts like lint:js:fix, the addition of extra extensions on the right side allows for further coverage.

You might wonder why we specify extensions on the left for lint-staged and on the right for lint:js:fix? The extensions on the right side are not strictly necessary (as far as I know) since lint-staged only executes commands for the specified extensions on the left. However, being explicit about targeted extensions enhances clarity and enables running npm run lint:js:fix in the CLI without triggering errors on unhandled files such as .txt, .json, .md, or .jpg.

Experimentation is key here—if unsure, consider testing different setups to find the most efficient solution for your needs.

  1. "**/*.{vue,js,jsx,ts,tsx}": "eslint --fix"
    . This configuration may function effectively based on previous explanations, although I haven't personally tested it.
Exploring other file extensions

For .html files, they should be minimal within your Vue project. Utilize W3C validator to ensure compliance if necessary. In terms of HTML within template tags in your .vue files, these sections will undergo proper ESlint checks. Incorporating Prettier complements this setup, offering convenient auto-formatting capabilities once a team-wide .prettierrc configuration is established.

As for .json files, ESlint doesn't handle them natively. To lint/format .json or other specific extensions, explore relevant NPM packages that suit your requirements and integrate them into your pipeline using configurations like

"**/*.json": ["npm run lint-my-json-please"]
.

Ultimately, husky and lint-staged streamline tasks that could manually be performed via the CLI. If you're satisfied with manual execution and results, transitioning to automation requires identifying suitable packages and configuring them accordingly.


In your package.json, consider including the following:

"scripts": {
  "lint:js": "eslint . --ext .js,.vue",
  "lint:js:fix": "eslint --ext .js,.vue --fix",
},

In your .lintstagedrc:

{
  "**/*.{js,vue}": ["npm run lint:js:fix"]
}

In .husky/pre-commit:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npm run lint-staged

In .husky/commit-msg:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx --no-install commitlint --edit ""

Consider setting up ESlint error tracking in VSCode for real-time monitoring and automatic formatting upon saving files.

Now, either manually run npm run lint:js for issue detection, or let husky execute lint-staged and apply eslint --fix exclusively to modified .js and .vue files during commits.

Your commitlint.config.js configuration should suffice!


To recap, lint:js examines all JS and Vue files, whereas during commits triggered by husky and lint:js:fix, only touched files undergo linting—this exemplifies the essence of selective linting facilitated by lint-staged.

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

Adjust the height of images to be consistent

I'm currently working on creating a grid layout with 4 images in a row using DaisyUI card component. However, I've run into an issue where there is white space at the bottom of some images due to varying image heights. Is there a solution that wo ...

React-Image-Annotate encountered an issue: SyntaxError - The import statement cannot be used outside a module

Encountering an issue while trying to set up react-image-annotate. Here is the problem I am facing initially: https://i.stack.imgur.com/XgYPd.png This is how I have implemented it: import React from 'react' import ReactImageAnnotate from ' ...

What is the method for retrieving the name of a canceled file?

When a user clicks on the "Cancel" button during an upload, I am attempting to retrieve the filename of the file that was canceled. However, it seems like the current method I am using (var image_file_name) is not successfully retrieving the name of the ca ...

"Efficiently transferring a large file using AJAX and sending it via POST to a

I am facing a challenge with a small script that I am developing. The script is designed to download relatively large files (around 15Mb each) from one domain using AJAX, and then upload/post them to another domain also through AJAX. Downloading the files ...

Guide to eliminating the clearable icon in the Vuetify file input

I am struggling to find any props to deactivate the clearable icon. Additionally, there doesn't seem to be an event related to this issue. Is there a method available to eliminate the clearable icon? <v-file-input ref="profilePictureFileInput" ...

Reactjs encountering issues with CSS loading correctly

Currently, I am working with reactjs and utilizing the Nextjs framework. All my "css, js, images" are stored in the "public" folder and have been included in "_app.js". However, whenever I attempt to load the "Main page" in a browser, the page does not d ...

Learn how to implement pagination in AngularJS using the $http service

I need assistance in implementing pagination using Angularjs within the Ionic Framework. Can someone provide guidance on how to code pagination for fetching data from a JSON URL? controller.js angular.module('starter.controllers', []) .control ...

ERROR_UNSUPPORTED_ESM_URL_SCHEME - issue with next-sitemap plugin

I have a project utilizing next-sitemap with Node.js version v14.11.0. next-sitemap.config.js module.exports = { siteUrl: 'https://*****.com', generateRobotsTxt: true, robotsTxtOptions: { additionalSitemaps: [ 'htt ...

Vue-ctk-date-time-picker: Your Ultimate Date and Time Selection Tool for Vue

After spending the last 6 hours trying to solve this issue, I am reaching out for some assistance. I have been using the DateTime picker vue-ctk-date-time-picker, which can be found on GitHub at https://github.com/chronotruck/vue-ctk-date-time-picker In ...

argument sent to component yields a result of undefined value

I am struggling with an asynchronous method that needs to be called in order to render a value on the first cycle. However, it seems that the component is being rendered before the value is returned, resulting in the prop being undefined when passed to the ...

Steps for implementing Onclick event within the <Script> tag to display a div:

I am currently working on a code that allows me to show and hide a <div> element after clicking on an advertisement from any website. This advertisement is generated by a script. How can I implement the onclick event within the <script> tag? T ...

A method to use jQuery to replace newlines with commas in user input

Input Processing Challenge <input> Whenever there is multi-line text pasted into the input field, I need to replace newlines (\r, \n, and \r\n) as well as tabs \t with commas ,. This scenario mainly occurs when users copy c ...

"Displaying 'Object Object' as a title when hovering over an element

I am currently using an accordion element to display several FAQs on a webpage. The code snippet for the accordion with content is as follows: { Object.keys(FAQS).map((key, index) => { return ( <div key={key}> ...

Issue with Angular ngModel not syncing with variable changes

Currently using Angular 4 and Typescript, I have a table containing <select> elements in my template: <tr *ngFor="let task of tasksDetails"> <td>{{task.name}}</td> <td> <select class="form-control" [(ngMode ...

Dynamic text input and selection menu with AJAX (PHP and JavaScript)

As a student who is new to Javascript and PHP, I am trying to create a login page for my website that can verify user input in the database using AJAX. For example, when a user enters their username and password, the system should automatically check if t ...

Is there any way to remove the two default aspNetHidden Divs in asp.net web forms?

After creating an empty webform page in asp.net, the generated code looks like this: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Threetier.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org ...

Steps to remove information from a database using PHP, AJAX, and vanilla JavaScript (without jQuery)

I am facing an issue with deleting data from my database. Whenever I click on the delete button, it deletes the first row instead of the intended row. Below is my PHP code: <?php $connect = mysqli_connect("localhost","root","","abu"); if($conne ...

I am encountering an issue with my Laravel Vue application where it is not able to delete a record. Should I consider binding my button to ensure it redirects to the controller

Hello, I am facing an issue while working on my app that involves a simple CRUD operation. The problem is that the code does not delete a record when I click the delete button. I am new to Laravel and Vue, so I am still getting familiar with how these two ...

The player clicks once and the game is played two times

Struggling with a coding issue here. I've got some code where you click on an image and if it can be moved to the next cell, it should move. function changecell(a){ var moved=false; if(a%3 !=0) { if(ij[a-1]==0) { moved=true; ...

JavaScript array error - unrecognized symbol

Hello, I am attempting to generate an array of errors and showcase them all at once. Here is my code: if (!first_name) { var error[] = "Please fill in the Last Name"; $('#first_name').addClass('error'); } else { $('#fi ...