DE EN ES FR ID JA KO PT RU TH VI ZH

インストール

CheerioはNode.js環境専用に設計されたjQueryコアのサーバーサイド実装です。このガイドでは、プロジェクトにCheerioをインストールしてセットアップする全ての方法について説明します。

package managerを使用したインストール

npm

npm install cheerio

yarn

yarn add cheerio

pnpm

pnpm add cheerio

bun

bun add cheerio

importの構文

ESM (ES Modules) - 推奨

import * as cheerio from 'cheerio';

// Load HTML and create a Cheerio instance
const $ = cheerio.load('<h2 class="title">Hello world</h2>');

// Manipulate elements
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');

console.log($.html());
// => <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>

CommonJS

const cheerio = require('cheerio');

const $ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');

分割代入import

// Import specific functions
import { load, contains, merge } from 'cheerio';

const $ = load('<ul><li>Apple</li><li>Orange</li></ul>');

TypeScriptのセットアップ

CheerioにはTypeScript定義が組み込まれています。追加で@types packageをインストールする必要はありません。

基本的なTypeScriptの使用方法

import * as cheerio from 'cheerio';
import type { CheerioAPI, Element } from 'cheerio';

const html = '<div class="container"><p>Hello</p></div>';
const $: CheerioAPI = cheerio.load(html);

// Type-safe element selection
const elements: cheerio.Cheerio<Element> = $('.container p');
const text: string | undefined = elements.text();

高度な型の使用方法

import type { AnyNode, CheerioOptions } from 'cheerio';

const options: CheerioOptions = {
  xmlMode: true,
  decodeEntities: false
};

const $ = cheerio.load('<xml><item>data</item></xml>', options);

環境サポート

Node.js要件

ブラウザでの制限

⚠️ 重要: Cheerioはブラウザ環境向けに設計されていません。以下の理由により、サーバーサイドライブラリです:

ブラウザ環境では、jQueryまたはモダンなDOM APIを使用してください。

高度な読み込み方法

Bufferからの読み込み

import * as cheerio from 'cheerio';
import * as fs from 'fs';

// Load from buffer with encoding detection
const buffer = fs.readFileSync('index.html');
const $ = cheerio.loadBuffer(buffer);

URLからの読み込み

import * as cheerio from 'cheerio';

// Fetch and parse HTML from a URL
const $ = await cheerio.fromURL('https://example.com');
console.log($('title').text());

HTMLのストリーミング

import * as cheerio from 'cheerio';
import * as fs from 'fs';

// Parse HTML streams
const writeStream = cheerio.stringStream({}, (err, $) => {
  if (err) {
    console.error('Parse error:', err);
    return;
  }
  
  console.log($('h1').text());
});

fs.createReadStream('document.html', { encoding: 'utf8' })
  .pipe(writeStream);

設定オプション

パーサーオプション

import * as cheerio from 'cheerio';

const $ = cheerio.load(html, {
  // Use XML mode for XML documents
  xmlMode: false,
  
  // Decode HTML entities
  decodeEntities: true,
  
  // Set base URI for resolving relative URLs
  baseURI: 'https://example.com',
  
  // Enable/disable scripting
  scriptingEnabled: false
});

よくあるインストールの問題

Node.jsバージョンの競合

エラー: Cannot find module 'cheerio'または互換性警告

解決方法: Node.js 18.17以上を使用していることを確認してください:

node --version
# Should show v18.17.0 or higher

# Update Node.js if needed
npm install -g n  # For Unix systems
n latest

ESM/CommonJS moduleの問題

エラー: require() of ES ModuleまたはCommonJSでのimport

解決方法: package.jsonに正しいmoduleタイプが設定されていることを確認してください:

{
  "type": "module"
}

または、環境に適したimport構文を使用してください。

TypeScript設定

エラー: Cheerioの型によるTypeScriptコンパイルエラー

解決方法: tsconfig.jsonを更新してください:

{
  "compilerOptions": {
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true
  }
}

大きなドキュメントでのメモリ問題

エラー: JavaScript heap out of memory

解決方法: Node.jsのメモリ制限を増やしてください:

node --max-old-space-size=4096 your-script.js

または、ストリーミング方法を使用してより小さなチャンクでドキュメントを処理してください。

エンコーディングの問題

エラー: 解析されたHTMLの文字エンコーディングが正しくない

解決方法: 明示的なエンコーディングオプションでloadBuffer()を使用してください:

const $ = cheerio.loadBuffer(buffer, {
  encoding: {
    defaultEncoding: 'utf8'
  }
});

検証

インストールが正しく動作することを確認してください:

import * as cheerio from 'cheerio';

const $ = cheerio.load('<h1>Test</h1>');
console.log($('h1').text()); // Should output: "Test"

// Check version
console.log('Cheerio version:', cheerio.version || 'Version info not available');

これらのインストール手順により、Node.jsアプリケーションでCheerioの強力なjQuery風APIを使用してHTMLの解析と操作を開始する準備が整いました。