Establishing a pre-commit hook for Husky to utilize Prettier in Angular applications

I am referring to a tutorial on how to set up a Husky pre-commit hook for Prettier in a new Angular project. I want the project files to be automatically formatted to match the committed files, but it seems like something may be missing.

The tutorial suggests configuring Husky like this:

  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.ts": [
      "prettier - write",
      "git add"
    ]
  },

After installing Husky and Prettier with npm i -D husky prettier, I created a src/app/test.ts file to test it out. However, nothing happened when I tried to commit the unformatted content of test.ts file.

How can we make sure that the pre-commit hook is triggered to format the files before committing?

Answer №1

Alright, here is the breakdown of the process.

ng new ngtestprettierhook --style=scss
cd ngtestprettierhook
npm install -D prettier husky
npx husky init

Next, execute the following command (refer to Option 1 instructions on Prettier's website):

npx mrm@2 lint-staged

Your pre-commit file will now resemble this:

ng test --watch=false --browsers=ChromeHeadless
npx lint-staged

Don't forget to update the permissions for the pre-commit script in the husky directory.

chmod u+x .husky/pre-commit

In your package.json, include formatting rules for typescript files as shown below:

"lint-staged": {
  "*.{js,ts,css,md}": "prettier --write"
}

Create a src/app/test.ts file with the provided content:

export class Test { nf:string = "not formatted"     }

Finally, commit your changes by running

git add . && git commit -m "Test"
.

You'll see that the test.ts file has been correctly formatted.

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

Arrange a JavaScript map based on its values and ensure that a specific field index remains at the top position

I'm sure this question may seem simple to some, but as a JavaScript novice, I couldn't find the answer myself. Here is the code snippet I'm working with: Let map = new Map<String,String> map.set('0', select) map.set('1&a ...

"Tempus Dominus now offering a seamless experience without the need for an

The example code provided seems to be malfunctioning: <button id="idbtn"> $('#idbtn').datetimepicker(); ...

JavaScript - Combine objects by summing values with matching keys

Below is the given array : [ { "Date": "2019.07.08", "Organisation": "A", "Client": "Client1", "Product": "Pen", "Quantity": "1120" }, { "Date": "2019.07.08", "Organisation": "A", "Client": "Client1", "Product": " ...

Tips for effectively utilizing codelyzer within Angular 2

Looking to integrate codelyzer in my project without webpack and using systemjs. I included a tslint configuration but when running npm start, no errors are being detected even though the correct style guide hasn't been followed. What steps should I ...

Next.js: Generating static sites only at runtime due to getStaticProps having no data during the build phase, skipping build time generation

I am looking to customize the application for individual customers, with a separate database for each customer (potentially on-premise). This means that I do not have access to any data during the build phase, such as in a CI/CD process, which I could use ...

Show the day of the week

I'm seeking a solution to display the upcoming Friday of each week within Wordpress. We were able to achieve this in the past using the code below on non-Wordpress platforms, but it seems outdated and no longer functional. For example: This week&apos ...

What is the best way to create exclusive toggle buttons using jQuery?

I am currently working on a project where I need to create functionality for three buttons, each triggering a unique graph effect. The key requirement is that when one button is pressed, the other two should be deactivated along with their corresponding fu ...

Deactivate a span in real-time using ng-model

I found a helpful guide on creating a custom editable <span> using ngModelController here: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#example Now, I am looking to implement a feature that allows me to dynamically disable editin ...

Determine the generic parameter of the output type by analyzing the resolved value of a data type within the function

I am looking to automatically determine the generic parameter of the return type by utilizing the resolved value of a type within the function. Consider the following: export type Context = any; export type Handler<T> = (ctx: Context) => Promise& ...

How to effectively trigger a function to load images in React

When my react app loads, I want the images to load immediately. This involves calling the function collectionChanged(e.target.value) on application start. Inside a .jsx file, there is a function named getHomePage() which contains 4 functions. Upon calling ...

Divide the toggle buttons into separate rows for better organization

Snippet: <mat-button-toggle-group value="0" (change)="toggleChangeQuestion($event)" name="selectQuestions" #group2="matButtonToggleGroup"> <div *ngFor="let item of test; let i = index;"> ...

Confirming the authenticity of a property within one entity by comparing it to a property within another entity

When validating two objects, sending and receiving countries, it is important to ensure that they are not identical. Specifically, we want to check if the receiving country is the same as the sending country and if it is, return an error message. The fol ...

Is there a way to update and save both dependencies and devDependencies with a single command in Npm?

Is there a way to update multiple npm dependencies and save them to their respective locations in the package.json file? This is what my package.json looks like: { "dependencies": { "gulp": "^3.0.0" }, "devDependencies": { "gulp-eslint" ...

Using Rails to render a partial containing a form object

I need help with rendering a partial called 'colordata' after selecting a color from a dropdown list using Ajax. Unfortunately, I'm not seeing any changes on the main page and the form is undefined in the colordata partial. This is the sche ...

How can I prevent a browser from allowing users to select an image tag?

I'm dealing with an issue on my webpage where I have an image that is inadvertently picking up mouse clicks, causing the browser to perform drag and drop actions or highlight the image when clicked. I really need to use the mousedown event for somethi ...

Angular is able to successfully retrieve the current route when it is defined, but

Here's the code snippet I am working with: import { Router } from '@angular/router'; Following that, in my constructor: constructor(router: Router) { console.log(this.router.url); } Upon loading the page, it initially shows the URL a ...

Creating a popup using JavaScript in an ASP.NET page can be challenging when it comes to passing values

The list page in my parent window displays multiple rows, each representing an individual person. Next to each person's name is an icon that links to the "change status" page. When clicking on the icon, a popup page should open where the status of th ...

Determine the specific button that was clicked within a React component

I have a challenge with dynamically generated material UI buttons. I am trying to identify which button was clicked by obtaining the value of the name attribute that I assigned to each button. Is there a way to accomplish this? In essence, I need to retrie ...

Unable to send parameters via URL when making an Ajax request in Rails

Struggling to pass a parameter through a URL in an Ajax request that's triggered by a confirmation dialog. Need the value of that parameter in my Rails controller upon successful request but can't seem to make it work. Tried the following code s ...

Issue encountered while trying to install Angular2 using NPM

My attempts to install Angular2 through Terminal have been met with some errors. I have verified that Node and NPM are both current. Screenshot of the Terminal As a newcomer, any assistance would be greatly appreciated. Thank you, Spen ...