Intermediate

Transformers.js

Run state-of-the-art Hugging Face transformer models directly in the browser — no server required. Supports text, image, audio, and multimodal tasks.

What is Transformers.js?

Transformers.js is the JavaScript port of Hugging Face's popular transformers Python library. It runs ONNX-converted models in the browser using WebAssembly or WebGPU, supporting 1000+ pre-trained models.

Installation

Terminal
npm install @huggingface/transformers

Sentiment Analysis

JavaScript
import { pipeline } from '@huggingface/transformers';

// Create a sentiment analysis pipeline
const classifier = await pipeline(
  'sentiment-analysis',
  'Xenova/distilbert-base-uncased-finetuned-sst-2-english'
);

const result = await classifier('I love this product!');
console.log(result);
// [{ label: 'POSITIVE', score: 0.9998 }]

// Batch processing
const results = await classifier([
  'This is amazing!',
  'Terrible experience.',
  'It was okay, nothing special.'
]);

Text Generation

JavaScript
const generator = await pipeline(
  'text-generation',
  'Xenova/gpt2'
);

const output = await generator('The future of AI is', {
  max_new_tokens: 50,
  temperature: 0.7
});
console.log(output[0].generated_text);

More Pipeline Tasks

JavaScript
// Question answering
const qa = await pipeline('question-answering');
const answer = await qa({
  question: 'What is the capital of France?',
  context: 'France is a country in Europe. Its capital is Paris.'
});

// Text summarization
const summarizer = await pipeline('summarization');
const summary = await summarizer(longText, { max_length: 100 });

// Image classification
const imageClassifier = await pipeline('image-classification');
const result = await imageClassifier('https://example.com/cat.jpg');

// Feature extraction (embeddings)
const extractor = await pipeline('feature-extraction');
const embeddings = await extractor('Hello world');

Supported Tasks

TaskExample ModelUse Case
sentiment-analysisdistilbert-sst2Review classification
text-generationgpt2, phi-3Content creation, chatbots
summarizationdistilbart-cnnArticle summaries
translationopus-mtLanguage translation
image-classificationvit-basePhoto categorization
object-detectiondetr-resnet-50Finding objects in images
speech-to-textwhisper-tinyTranscription
Performance tip: Models are downloaded and cached in the browser on first use. Subsequent loads are instant. Use quantized models (ONNX int8) for faster inference and smaller download sizes.