npm package: @gringow/gringow-vite
Description: A Vite plugin for Gringow AI-powered translation tool
Author: Renato Gaspar
Latest version: 0.3.0

# @gringow/gringow-vite

[![npm version](https://img.shields.io/npm/v/@gringow/gringow-vite)](https://www.npmjs.com/package/@gringow/gringow-vite)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

Vite plugin for Gringow that automatically extracts translation strings during development and build. Scans your source code for `g` tagged templates, manages cache synchronization, and provides CLI flags for cache maintenance.

## Features

- 🔍 **Automatic Extraction** - Finds `g` and `gid` tagged templates in your code
- 🔄 **Cache Synchronization** - Keeps translations in sync with source code
- 🧹 **Smart Cleanup** - Removes unused translations automatically
- ⚡ **Build-Time Translation** - Generates cache during Vite builds
- 🛠️ **CLI Flags** - `--gringow=build|clear|reset` for cache management
- 📦 **Vite 7 Compatible** - Works with latest Vite version

## Installation

```bash
# Using pnpm (recommended)
pnpm add -D @gringow/gringow @gringow/gringow-vite

# Using npm
npm install -D @gringow/gringow @gringow/gringow-vite

# Using yarn
yarn add -D @gringow/gringow @gringow/gringow-vite
```

## Quick Start

### 1. Add Plugin to Vite Config

```typescript
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import Gringow from '@gringow/gringow-vite'

export default defineConfig({
  plugins: [
    react(),
    Gringow({ debug: false })
  ]
})
```

### 2. Create Gringow Config (Optional)

```javascript
// gringow.config.js
export default {
  llm: {
    provider: 'openai',
    apiKey: process.env.OPENAI_API_KEY,
    model: 'gpt-4o-mini',
  },
  languages: ['pt-BR', 'es-ES', 'fr-CA'],
  sourceLanguage: 'en-US',
  globby: './src/**/*.{js,jsx,ts,tsx}', // Files to scan
}
```

### 3. Use in Your Code

```tsx
// App.tsx
import { g } from '@gringow/gringow-react/vite'

export default function App() {
  return <h1>{g`Welcome to Gringow`}</h1>
}
```

### 4. Build or Develop

```bash
# Development mode - extracts translations on the fly
pnpm run dev

# Build mode - generates complete cache
pnpm run build
```

The plugin automatically:
- Scans your source files for `g` and `gid` tagged templates
- Generates translations using configured LLM
- Writes to `./gringow/gringow.json`
- Updates cache as you code

## CLI Flags

Control cache lifecycle with special flags during Vite builds or dev server startup.

### Build Cache

Scan all source files and generate complete translation cache.

```bash
vite build --gringow=build

# Useful for:
# - CI/CD pipelines
# - Initial cache generation
# - Pre-deployment translation updates
```

### Clear Cache

Delete the entire cache file and exit.

```bash
vite build --gringow=clear

# Use when:
# - Starting fresh
# - Cleaning up old translations
# - Debugging cache issues
```

### Reset Cache

Clear existing cache and rebuild from scratch in one command.

```bash
vite build --gringow=reset

# Equivalent to:
# vite build --gringow=clear && vite build --gringow=build
```

**Note**: These commands exit immediately after completing the operation, making them perfect for CI scripts.

## Configuration

### Plugin Options

```typescript
interface GringowVitePluginOptions {
  debug?: boolean  // Log plugin operations (default: false)
}
```

**Example:**
```typescript
Gringow({ debug: true }) // Logs file scanning and extraction
```

### Gringow Config Options

The plugin reads your `gringow.config.js` for:

- **`globby`** - File pattern to scan (default: `'./src/**/*.{js,jsx,ts,tsx}'`)
- **`cache.dir`** - Cache directory (default: `'./gringow'`)
- **`cache.file`** - Cache filename (default: `'gringow.json'`)
- **`llm.*`** - LLM provider configuration
- **`languages`** - Target languages array

See [@gringow/gringow](https://www.npmjs.com/package/@gringow/gringow) for full config schema.

## How It Works

The plugin hooks into Vite's transform pipeline:

### Transform Hook

- **Scans modules** - Checks each transformed file for `g` tagged templates
- **Extracts strings** - Parses template literals from `g`/`gid` tags
- **Generates IDs** - Creates content-based cache IDs
- **Calls core library** - Invokes `@gringow/gringow` to translate and cache

### Build End Hook

- **Static analysis** - Scans all files matching `globby` pattern
- **Cache pruning** - Removes translations no longer in source code
- **Backfill** - Ensures all discovered strings are translated

### Build Start Hook

- **CLI flag detection** - Watches for `--gringow=build|clear|reset`
- **Cache operations** - Executes maintenance tasks
- **Early exit** - Terminates Vite after flag operations

## Usage Examples

### Basic React + Vite Setup

```typescript
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import Gringow from '@gringow/gringow-vite'

export default defineConfig({
  plugins: [react(), Gringow()]
})
```

```tsx
// src/App.tsx
import { g } from '@gringow/gringow-react/vite'

export default function App() {
  const user = { name: 'Alice' }
  return (
    <div>
      {g`Hello ${user.name}!`}
      {g`Welcome to our platform`}
    </div>
  )
}
```

### CI/CD Pipeline

```yaml
# .github/workflows/deploy.yml
- name: Generate translations
  run: pnpm vite build --gringow=build

- name: Build application
  run: pnpm vite build
```

### Custom File Patterns

```javascript
// gringow.config.js
export default {
  // Scan TypeScript files only
  globby: './src/**/*.{ts,tsx}',

  languages: ['pt-BR', 'es-ES'],
}
```

### Multi-Environment Setup

```typescript
// vite.config.ts
import { defineConfig } from 'vite'
import Gringow from '@gringow/gringow-vite'

export default defineConfig(({ mode }) => ({
  plugins: [
    Gringow({
      debug: mode === 'development'
    })
  ]
}))
```

## Development scripts
```bash
pnpm run build   # Emit dist/ with tsup
pnpm run watch   # Continuous rebuild for local development
```

## License
MIT © Renato Gaspar

## Best Practices

1. **Run build flag before deployment** - `vite build --gringow=build` ensures complete cache
2. **Gitignore cache file** - Add `/gringow/gringow.json` to `.gitignore` if regenerating in CI
3. **Or commit cache** - Commit cache file for faster deploys without LLM calls
4. **Use glob patterns wisely** - Exclude test files and node_modules
5. **Enable debug mode** - Use `debug: true` when troubleshooting extraction issues

## Troubleshooting

### Translations Not Extracted

```typescript
// ❌ Won't work - not using g tag
const text = `Hello world`

// ✅ Works - using g tag
const text = g`Hello world`
```

### Cache Not Updating

```bash
# Clear and rebuild
pnpm vite build --gringow=reset

# Or manually delete
rm -rf gringow/gringow.json
```

### Missing Translations

Check your `globby` pattern includes all source files:

```javascript
// gringow.config.js
export default {
  globby: './src/**/*.{js,jsx,ts,tsx}', // Adjust to your structure
}
```

## Development

```bash
# Install dependencies
pnpm install

# Build the plugin
pnpm run build

# Watch mode
pnpm run watch
```

## Related Packages

Gringow provides a complete ecosystem for AI-powered translation:

- **[@gringow/gringow](https://www.npmjs.com/package/@gringow/gringow)** - Core translation library
- **[@gringow/gringow-vite](https://www.npmjs.com/package/@gringow/gringow-vite)** - Vite plugin for build-time extraction
- **[@gringow/gringow-react](https://www.npmjs.com/package/@gringow/gringow-react)** - React hooks and components
- **[@gringow/gringow-shadow](https://www.npmjs.com/package/@gringow/gringow-shadow)** - Web Component layer
- **[@gringow/gringow-cli](https://www.npmjs.com/package/@gringow/gringow-cli)** - CLI tool
- **[@gringow/gringow-nextjs](https://www.npmjs.com/package/@gringow/gringow-nextjs)** - Next.js plugin (experimental)

## Resources

- [Documentation](https://gringow.dev)
- [GitHub Repository](https://github.com/rntgspr/gringow)
- [Example: Vite + React](https://github.com/rntgspr/gringow/tree/main/example-gringow-vite)

## License

MIT © [Renato Gaspar](https://github.com/rntgspr)

---

**Questions?** Open an issue on [GitHub](https://github.com/rntgspr/gringow/issues)