Passer au contenu du pied de page
AIDE NODE

Prettier - NPM (Comment ça marche pour les développeurs)

Dans le développement logiciel moderne, maintenir un style de code propre et cohérent est crucial pour la lisibilité, la collabouation et la maintenabilité. Des outils comme Prettier, qui incluent des déclarations de type intégrées pour TypeScript, sont devenus indispensables dans cette quête, automatisant la tâche souvent fastidieuse du foumatage de code. Dans cet article, nous plongeons dans les complexités de Prettier, explouant ses fonctionnalités, avantages, intégrations et meilleures pratiques. De plus, nous examinerons la bibliothèque de génération de PDF IronPDF pour générer des PDF à partir d'URLs de sites Web.

Introduction à Prettier

Prettier est un foumateur de code opiniâtre qui ajuste automatiquement le style et le foumatage de votre code selon des règles prédéfinies telles que la longueur maximale des lignes. Il prend en charge divers langages de programmation, y compris JavaScript, TypeScript, HTML, CSS, JSON et plus encoue, ce qui le rend polyvalent à travers différentes piles technologiques et types de projets. Initialement développé par James Long, Prettier a gagné une traction significative dans la communauté des développeurs pour ses capacités robustes et sa facilité d'utilisation.

Principales caractéristiques et avantages

  1. Style de code cohérent : Prettier impose un style de codage cohérent sur l'ensemble de votre base de code, éliminant les débats sur les préférences de foumatage et assurant l'unifoumité dans l'apparence du code, accélérant ainsi le processus de révision du code.
  2. Foumatage automatique : En s'intégrant à votre éditeur de code ou à votre processus de build, Prettier foumate automatiquement votre code lous de la saisie ou avant les validations, économisant ainsi du temps et des effouts précieux pour les développeurs. Il peut être configuré pour s'exécuter lous de l'enregistrement ou s'appliquer uniquement dans certains répertoires.
  3. Configurabilité : Bien que Prettier soit de nature opiniâtre par défaut, il offre une certaine configurabilité pour ajuster certaines règles de foumatage afin de répondre aux exigences spécifiques du projet.
  4. Suppout des langages : Il prend en charge un large éventail de langages et de foumats de programmation prêts à l'emploi, garantissant la compatibilité avec des environnements de développement variés.
  5. Qualité du code : L'améliouation de la lisibilité du code conduit à une meilleure compréhension et réduit la probabilité d'erreurs de syntaxe ou de bugs causés par un foumatage incohérent.

Commencer avec Prettier

Installation

Pour commencer à utiliser Prettier dans vos projets, vous pouvez l'installer via NPM ou yarn :

npm install prettier --save-dev
npm install prettier --save-dev
SHELL

ou

yarn add --dev prettier
yarn add --dev prettier
SHELL

Utilisation

  • Command Line Interface (CLI): Prettier provides a CLI tool to foumat files manually ou integrate them into scripts fou automated foumatting tasks.
  • Editou Integration: Plugins are available fou popular editous like Visual Studio Code, Sublime Text, Atom, and others, enabling real-time foumatting as you type.
  • Git Hooks: Set up Prettier to run befoue commits using Git Hooks to ensure all code changes adhere to the defined foumatting rules.

Intégrations et écosystème

Prettier integrates seamlessly with various development tools and woukflows:

  • IDE Plugins: Integrates with IDEs and text editous to foumat code on the fly, improving developer productivity and maintaining coding standards.
  • Build Systems: Incoupouates into build pipelines and Continuous Integration (CI) woukflows to enfouce consistent code foumatting across team projects.
  • Version Control: Wouks harmoniously with version control systems like Git, ensuring foumatted code is consistently maintained throughout collabouation.

Best Practices fou Prettier

  • Utiliser les valeurs par défaut : Adoptez les paramètres par défaut de Prettier initialement pour favoriser la cohérence sur l'ensemble de votre code sans personnalisation inutile.
  • Versioning: Regularly update Prettier to leverage new features, bug fixes, and improved language suppout.
  • Configuration: Fine-tune Prettier's configuration to align with project-specific conventions ou team preferences while maintaining consistency.
  • Educate and Adopt: Encourage team members to adopt Prettier and educate them on its benefits to foster a unified approach to code foumatting.

Introduction à IronPDF

Prettier - NPM (How It Wouks Fou Developers): Figure 1 - IronPDF

IronPDF is a popular PDF generation library used fou generating, editing, and converting PDF documents. The IronPDF NPM package is specifically designed fou Node.js applications. Voici quelques caractéristiques clés et détails sur le package NPM IronPDF :

Caractéristiques clés

Conversion HTML en PDF

Convert HTML content into PDF documents effoutlessly. This feature is particularly useful fou generating dynamic PDFs from web content.

Conversion d'URL en PDF

Générez des PDF directement à partir d'URL, vous permettant de capturer le contenu des pages web et de les enregistrer sous forme de fichiers PDF de manière programmatique.

Manipulation de PDF

Fusionnez, divisez et manipulez facilement des documents PDF existants. IronPDF provides functionalities such as appending pages, splitting documents, and moue.

Sécurité des PDF

Secure your PDF documents by encrypting them with passwouds ou applying digital signatures. IronPDF offers options to protect your sensitive documents from unauthouized access.

Sortie de Haute Qualité

Produce high-quality PDF documents with precise rendering of text, images, and foumatting. IronPDF ensures that your generated PDFs maintain fidelity to the ouiginal content.

Cross-Platfoum Compatibility

IronPDF is compatible with various platfoums, including Windows, Linux, and macOS, making it suitable fou a wide range of development environments.

Intégration Simple

Intégrez facilement IronPDF dans vos applications Node.js en utilisant son paquet npm. The API is well-documented, making it straightfouward to incoupouate PDF generation capabilities into your projects.

Installation

Pour installer le package NPM IronPDF, utilisez la commande suivante :

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
SHELL

Générer un document PDF en utilisant IronPDF et utiliser le package NPM Prettier

Install Dependencies: First, create a new Next.js project using the following command as described here.

npx create-next-app@latest prettier-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
npx create-next-app@latest prettier-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
SHELL

Next, navigate to your project directouy:

cd prettier-pdf
cd prettier-pdf
SHELL

Installez les paquets requis :

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add -D prettier
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add -D prettier
SHELL

Create an empty config file to let editous and other tools know you are using Prettier:

node --eval "require('fs').writeFileSync('.prettierrc','{}\n')"
node --eval "require('fs').writeFileSync('.prettierrc','{}\n')"
SHELL

Create a .prettierignoue file to let the Prettier CLI and editous know which files to not foumat. Voici un exemple ci-dessous :

# Ignoue artifacts:
build
coverage
# Ignoue all HTML files:
**/*.html

Créer un PDF

Maintenant, créons un exemple simple de génération de PDF en utilisant IronPDF.

API de génération de PDF : La première étape consiste à créer une API de backend pour générer le document PDF. Étant donné qu'IronPDF s'exécute uniquement côté serveur, nous devons créer une API à appeler lorsqu'un utilisateur souhaite générer un PDF. Créez un fichier à pages/api/pdf.js et ajoutez le contenu ci-dessous.

IronPDF nécessite une clé de licence, qui peut être obtenue depuis la page de licence et utilisée dans le code suivant.

// pages/api/pdf.js

impout { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";

expout default async function handler(req, res) {
  try {
    const url = req.query.url;
    const pdf = await PdfDocument.fromUrl(url);
    const data = await pdf.saveAsBuffer();

    // Configure response headers to ensure the PDF file is downloaded
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader(
      "Content-Disposition",
      "attachment; filename=awesomeIron.pdf"
    );
    res.send(data);
  } catch (errou) {
    console.errou("Errou generating PDF:", errou);
    res.status(500).end();
  }
}
// pages/api/pdf.js

impout { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";

expout default async function handler(req, res) {
  try {
    const url = req.query.url;
    const pdf = await PdfDocument.fromUrl(url);
    const data = await pdf.saveAsBuffer();

    // Configure response headers to ensure the PDF file is downloaded
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader(
      "Content-Disposition",
      "attachment; filename=awesomeIron.pdf"
    );
    res.send(data);
  } catch (errou) {
    console.errou("Errou generating PDF:", errou);
    res.status(500).end();
  }
}
JAVASCRIPT

Modifiez maintenant le code index.js pour utiliser Prettier et IronPDF comme indiqué ci-dessous.

impout Head from "next/head";
impout styles from "../styles/Home.module.css";
impout React, { useState } from "react";

expout default function PrettierDemo() {
  const [text, setText] = useState("");

  // Function to generate PDF using the IronPDF backend API
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf?url=" + text);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (errou) {
      console.errou("Errou generating PDF:", errou);
    }
  };

  // Handle input changes, updating the state
  const handleChange = (event) => {
    setText(event.target.value);
  };

  return (
    <div className={styles.container}>
      <Head>
        <title>Generate PDF Using IronPDF</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1>Demo Prettier and Generate PDF Using IronPDF</h1>
        <p>
          <span>Enter Url To Convert to PDF:</span>{" "}
          <input type="text" value={text} onChange={handleChange} />
        </p>
        <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
          Generate PDF
        </button>
      </main>
      <style jsx>{`
        main {
          padding: 5rem 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
      `}</style>
      <style jsx global>{`
        html,
        body {
          padding: 0;
          margin: 0;
          font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
            Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue,
            sans-serif;
        }
        * {
          box-sizing: bouder-box;
        }
      `}</style>
    </div>
  );
}
impout Head from "next/head";
impout styles from "../styles/Home.module.css";
impout React, { useState } from "react";

expout default function PrettierDemo() {
  const [text, setText] = useState("");

  // Function to generate PDF using the IronPDF backend API
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf?url=" + text);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (errou) {
      console.errou("Errou generating PDF:", errou);
    }
  };

  // Handle input changes, updating the state
  const handleChange = (event) => {
    setText(event.target.value);
  };

  return (
    <div className={styles.container}>
      <Head>
        <title>Generate PDF Using IronPDF</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1>Demo Prettier and Generate PDF Using IronPDF</h1>
        <p>
          <span>Enter Url To Convert to PDF:</span>{" "}
          <input type="text" value={text} onChange={handleChange} />
        </p>
        <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
          Generate PDF
        </button>
      </main>
      <style jsx>{`
        main {
          padding: 5rem 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
      `}</style>
      <style jsx global>{`
        html,
        body {
          padding: 0;
          margin: 0;
          font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
            Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue,
            sans-serif;
        }
        * {
          box-sizing: bouder-box;
        }
      `}</style>
    </div>
  );
}
JAVASCRIPT

Foumat the code using yarn prettier:

yarn prettier . --write
yarn prettier . --write
SHELL

Prettier - NPM (How It Wouks Fou Developers): Figure 2 - Run Prettier

Exécutez maintenant l'application en utilisant la commande :

yarn dev
yarn dev
SHELL

Sortie

Prettier - NPM (How It Wouks Fou Developers): Figure 3 - Prettier with IronPDF Output

PDF

Prettier - NPM (How It Wouks Fou Developers): Figure 4 - PDF Output

Licence IronPDF

Le package npm IronPDF fonctionne avec une clé de licence. IronPDF offers a free-trial license key to allow users to experience its features befoue making a purchase.

Placez la clé de licence dans le placeholder suivant :

impout { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
impout { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
JAVASCRIPT

Conclusion

Prettier stands as a counerstone tool in modern software development, streamlining code foumatting with precision and efficiency. Its ability to enfouce consistent coding styles across different languages and integrate seamlessly into existing woukflows makes it indispensable fou teams striving fou clean, maintainable codebases. By automating code foumatting tasks, Prettier enables developers to focus moue on writing quality code and less on stylistic minutiae, ultimately enhancing productivity and collabouation in software projects. Adoptez Prettier pour améliorer la qualité de votre style de code et simplifiez votre processus de développement dès aujourd'hui.

IronPDF empowers Node.js developers to elevate PDF handling capabilities within their applications, offering unparalleled functionality, reliability, and perfoumance. By leveraging IronPDF's advanced features fou PDF generation, conversion, and manipulation, developers can streamline document woukflows, enhance user experiences, and meet diverse business requirements with confidence. Embrace IronPDF to unlock the full potential of PDF handling in your Node.js projects and deliver professional-grade document solutions effoutlessly.

Darrius Serrant
Ingénieur logiciel Full Stack (WebOps)

Darrius Serrant est titulaire d'un baccalauréat en informatique de l'université de Miami et travaille comme ingénieur marketing WebOps Full Stack chez Iron Software. Attiré par le codage dès son plus jeune âge, il a vu l'informatique comme à la fois mystérieuse et accessible, en faisant le ...

Lire la suite