npm package: @mlbrgn/translator
Description: A small JavaScript library to translate webpages into different languages
Author: Evertjan Garretsen
Latest version: 1.0.18

# Translator

docs generated using Junie AI

A small JavaScript library to translate webpages into different languages.

## Overview

Translator is a lightweight library that helps you implement multilingual support in your web applications. It can automatically detect the user's language, load translation files, and apply translations to your HTML elements.

## Key Features

- **Language Detection**: Automatically detects the user's preferred language based on browser settings
- **Persistence**: Optionally saves the selected language in localStorage
- **Dynamic Translation**: Translates elements added to the DOM after initial load using MutationObserver
- **Fallback Support**: Provides fallback language and translations when needed
- **Global Translation Function**: Exposes a global translation function for use in JavaScript
- **Flexible Configuration**: Customizable options for language paths, supported languages, and more

## Installation

```bash
npm install @mlbrgn/translator
```

## Usage

### Basic Setup

```javascript
import { Translator } from '@mlbrgn/translator';

const translator = new Translator({
  rootElement: document.body, // only searches for translatable items inside this element
  fallbackLanguage: 'en',
  detectLanguage: true,
  persist: true,
  languagesSupported: ['en', 'nl', 'fr'],
  languagesPath: '/lang'
});
```

### HTML Markup

Add `data-i18n` attributes to elements you want to translate:

```html
<h1 data-i18n="welcome">Welcome</h1>
<p data-i18n="intro">This text will be translated</p>

<!-- Translate attributes -->
<input data-i18n-placeholder="email" placeholder="Enter your email">

<!-- Translate with parameters -->
<p data-i18n="greeting" data-i18n-params='{"name":"John"}'>Hello, John!</p>
```

### Translation Files

Create JSON files for each language in your `languagesPath` directory:

```
/* File: /lang/en.json */
{
  "welcome": "Welcome",
  "intro": "This text will be translated",
  "email": "Enter your email",
  "greeting": "Hello, {{name}}!"
}
```

```
/* File: /lang/nl.json */
{
  "welcome": "Welkom",
  "intro": "Deze tekst wordt vertaald",
  "email": "Voer je e-mailadres in",
  "greeting": "Hallo, {{name}}!"
}
```

### Switching Languages

```javascript
// Switch to Dutch
translator.use('nl');

// Get current language
const currentLang = translator.activeLanguage;
```

### Using the Translation Function in JavaScript

```javascript
// If exposeFnName is set to '__' in the config
const message = __('welcome');

// Or use the translator instance directly
const message = translator._('welcome');

// With parameters
const greeting = translator._('greeting', { name: 'Jane' });
```

## Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| rootElement | Element | document | Element to search for translatable items |
| fallbackTranslations | Object | null | Used when fetching translations fails |
| fallbackLanguage | String | 'en' | Language to use when preferred language is not available |
| detectLanguage | Boolean | true | Whether to detect user's language from browser |
| persist | Boolean | false | Whether to save language preference in localStorage |
| persistKey | String | 'active_language' | Key to use for localStorage |
| languagesSupported | Array | ['en', 'nl'] | List of supported language codes |
| languagesPath | String | null | Path to translation JSON files |
| exposeFnName | String | '__' | Name of global translation function |
| debug | Boolean | false | Enable debug logging |

## Development

This package is developed inside the mlbrgn-node-workspace monorepo.
Do not run `npm run dev` or `npm install` inside this repository.

Clone the monorepo instead:
https://github.com/evertjanmlbrgn/mlbrgn-node-workspace