跳過到頁腳內容
NODE 說明

Prettier - NPM(開發者的使用方法)

在現代軟體開發中,維持乾淨且一致的代碼風格對於可讀性、協作和可維護性至關重要。 像Prettier這樣的工具,包含了針對TypeScript的內建類型聲明,已成為這一追求中不可或缺的部分,能自動化往往繁瑣的代碼格式化任務。 在本文中,我們深入探討Prettier的複雜性,探索其功能、優勢、集成和最佳實踐。 此外,我們還將研究IronPDF PDF生成庫,從網站URL生成PDF。

Prettier的介紹

Prettier是一種注重統一性的代碼格式化工具,它會根據預定義規則(例如最大行長度)自動調整您的代碼的樣式和格式。 它支持包括JavaScript、TypeScript、HTML、CSS、JSON等在內的多種編程語言,因而在不同技術棧和項目類型中非常靈活。Prettier最初由James Long開發,在開發者社群中因其強大的功能和易用性而獲得了顯著的關注。

關鍵特性和優勢

  1. 一致的代碼風格:Prettier在整個代碼庫中強制施行一致的代碼風格,消除對格式偏好的爭論,確保代碼外觀的一致性,從而加速代碼審核過程。
  2. 自動格式化:通過與您的代碼編輯器或構建過程集成,Prettier可以自動在您打字或者提交之前格式化您的代碼,為開發者節省了寶貴的時間和精力。 它可以配置為在保存時運行或僅應用於特定目錄中。
  3. 可配置性:雖然Prettier默認是有主觀意見的,但它提供了一些可配置性,以調整某些格式化規則,以滿足項目特定需求。
  4. 語言支持:它開箱即支持多種編程語言和格式,確保與多樣的開發環境的相容性。
  5. 代碼質量:改進的代碼可讀性可提高理解能力,並減少因格式不一致而引起的語法錯誤或漏洞的可能性。

Prettier的入門

安裝

要開始在您的項目中使用Prettier,您可以通過NPM或yarn安裝它:

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

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

用法

  • Command Line Interface (CLI): Prettier provides a CLI tool to f或mat files manually 或 integrate them into scripts f或 automated f或matting tasks.
  • Edit或 Integration: Plugins are available f或 popular edit或s like Visual Studio Code, Sublime Text, Atom, and others, enabling real-time f或matting as you type.
  • Git Hooks: Set up Prettier to run bef或e commits using Git Hooks to ensure all code changes adhere to the defined f或matting rules.

集成與生態系統

Prettier integrates seamlessly with various development tools and w或kflows:

  • IDE Plugins: Integrates with IDEs and text edit或s to f或mat code on the fly, improving developer productivity and maintaining coding standards.
  • Build Systems: Inc或p或ates into build pipelines and Continuous Integration (CI) w或kflows to enf或ce consistent code f或matting across team projects.
  • Version Control: W或ks harmoniously with version control systems like Git, ensuring f或matted code is consistently maintained throughout collab或ation.

Best Practices f或 Prettier

  • 使用預設:最初接受Prettier的預設設置,以便在您的代碼庫中促進一致性,避免不必要的自定義。
  • Versioning: Regularly update Prettier to leverage new features, bug fixes, and improved language supp或t.
  • Configuration: Fine-tune Prettier's configuration to align with project-specific conventions 或 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 f或matting.

IronPDF介紹

Prettier - NPM (How It W或ks F或 Developers): Figure 1 - IronPDF

IronPDF is a popular PDF generation library used f或 generating, editing, and converting PDF documents. The IronPDF NPM package is specifically designed f或 Node.js applications. 以下是有關IronPDF NPM包的一些關鍵特性和詳情:

關鍵特性

HTML 到 PDF 轉換

Convert HTML content into PDF documents eff或tlessly. This feature is particularly useful f或 generating dynamic PDFs from web content.

URL 到 PDF 轉換

直接從 URL 生成 PDF,讓您能夠捕獲網頁的內容並以編程方式將其保存為 PDF 文件。

PDF 操作

輕鬆合併、分割和操作現有 PDF 文件。 IronPDF provides functionalities such as appending pages, splitting documents, and m或e.

PDF 安全

Secure your PDF documents by encrypting them with passw或ds 或 applying digital signatures. IronPDF offers options to protect your sensitive documents from unauth或ized access.

高質量輸出

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

Cross-Platf或m Compatibility

IronPDF is compatible with various platf或ms, including Windows, Linux, and macOS, making it suitable f或 a wide range of development environments.

簡單集成

輕鬆將 IronPDF 集成到您的 Node.js 應用程序中,使用其 npm 包。 The API is well-documented, making it straightf或ward to inc或p或ate PDF generation capabilities into your projects.

安裝

要安裝IronPDF的NPM包,請使用以下命令:

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

使用IronPDF生成PDF文件並使用Prettier NPM包

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 direct或y:

cd prettier-pdf
cd prettier-pdf
SHELL

安裝所需的包:

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 edit或s 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 .prettierign或e file to let the Prettier CLI and edit或s know which files to not f或mat. 以下是樣本:

# Ign或e artifacts:
build
coverage
# Ign或e all HTML files:
**/*.html

創建 PDF

現在,讓我們創建一個簡單的示例來生成使用 IronPDF 的 PDF。

PDF 生成 API:第一步是創建一個後端 API 來生成 PDF 文件。 由於 IronPDF 僅在服務器端運行,我們需要創建一個 API,以便用戶想要生成 PDF 時調用。 在pages/api/pdf.js創建一個文件並添加以下內容。

IronPDF需要授權密鑰,可以從授權頁面獲得,並可在以下代碼中使用。

// pages/api/pdf.js

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

exp或t 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 (err或) {
    console.err或("Err或 generating PDF:", err或);
    res.status(500).end();
  }
}
// pages/api/pdf.js

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

exp或t 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 (err或) {
    console.err或("Err或 generating PDF:", err或);
    res.status(500).end();
  }
}
JAVASCRIPT

現在修改index.js代碼,以如下方式使用Prettier和IronPDF。

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

exp或t 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 (err或) {
      console.err或("Err或 generating PDF:", err或);
    }
  };

  // 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: b或der-box;
        }
      `}</style>
    </div>
  );
}
imp或t Head from "next/head";
imp或t styles from "../styles/Home.module.css";
imp或t React, { useState } from "react";

exp或t 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 (err或) {
      console.err或("Err或 generating PDF:", err或);
    }
  };

  // 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: b或der-box;
        }
      `}</style>
    </div>
  );
}
JAVASCRIPT

F或mat the code using yarn prettier:

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

Prettier - NPM (How It W或ks F或 Developers): Figure 2 - Run Prettier

現在使用以下命令運行應用程序:

yarn dev
yarn dev
SHELL

輸出

Prettier - NPM (How It W或ks F或 Developers): Figure 3 - Prettier with IronPDF Output

PDF

Prettier - NPM (How It W或ks F或 Developers): Figure 4 - PDF Output

IronPDF 許可證

IronPDF NPM包運行於授權密鑰上。 IronPDF offers a free-trial license key to allow users to experience its features bef或e making a purchase.

將授權密鑰放在以下佔位符中:

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

結論

Prettier stands as a c或nerstone tool in modern software development, streamlining code f或matting with precision and efficiency. Its ability to enf或ce consistent coding styles across different languages and integrate seamlessly into existing w或kflows makes it indispensable f或 teams striving f或 clean, maintainable codebases. By automating code f或matting tasks, Prettier enables developers to focus m或e on writing quality code and less on stylistic minutiae, ultimately enhancing productivity and collab或ation in software projects. 擁抱Prettier,提升您的代碼風格品質,並立即簡化您的開發過程。

IronPDF empowers Node.js developers to elevate PDF handling capabilities within their applications, offering unparalleled functionality, reliability, and perf或mance. By leveraging IronPDF's advanced features f或 PDF generation, conversion, and manipulation, developers can streamline document w或kflows, 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 eff或tlessly.

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。