JSPM

  • Created
  • Published
  • Downloads 178
  • Score
    100M100P100Q86792F
  • License ISC

A CLI for sheet-based translation focused on DX

Package Exports

  • @sheet-i18n/cli

Readme

@sheet-i18n/cli ✨

npm package View changelog

A CLI tool for efficient translation management using Google Sheets, with a focus on developer experience (DX).

Features

  • Initialize CLI configuration for translation workflows.
  • 👀 Watch files or directories for changes.
  • 📤 Register translation data to Google Sheets.
  • 🛠️ Built with TypeScript for type safety.

Core Concepts 🌟

😭 Traditional Translation Workflow

The traditional process of managing translations with Google Spreadsheets often includes these steps:

  1. Translator identifies the text to be translated from the page (without developer involvement).
  2. Translator adds the translation data to a Google Spreadsheet.
  3. Developer creates a script to locally download the translation data from the sheet.
  4. Developer inspects the translation data, matches it with the code, and finds the corresponding values in the source code (this can be time-consuming).
  5. If discrepancies exist between the spreadsheet and the code, developers request changes from the translator.
  6. Once resolved, the developer applies the translations using an internationalization (intl) library.
  7. For additional translations, developers manually import and apply them in the code.
  8. Results are checked on the page, and any errors prompt a repeat of the cycle.

This process is lengthy and redundant. Translators often lack visibility into how text is structured in code, especially when developers split strings, need to insert variables on the text, or add line breaks (<br/>). As a result, the translation burden falls back to the developers.

☺️ Developer-Centric Translation Workflow

This CLI streamlines the process by shifting the focus to developers:

  1. Developers identify and mark variables or text for translation directly in the code.
  2. Run the CLI to register changes (it automatically adds translations using Google Translate with support for Google Spreadsheets).
  3. Translators inspect and refine the translations for improved fluency and meaning on the Google Sheet.
  4. Developers import the confirmed translation data, completing the process.

With this approach, unnecessary back-and-forth is eliminated, and translations align seamlessly with code.

PreRequisite 📝

This library is tightly integrated with the @sheet-i18n/react package, which provides the React components needed for rendering translations efficiently. As a result, you must set up @sheet-i18n/react in your project before using this CLI.

1. Initialize i18n Store

This store will be used as a core translations module.

import en from './en.json';
import ko from './ko.json';

import { I18nStore } from '@sheet-i18n/react';

export const i18nStore = new I18nStore({
  supportedLocales: ['ko', 'en'],
  defaultLocale: 'ko',
  localeSet: {
    ko,
    en,
  },
  typeSafe: false, // optional (default: true)
});

💡 typeSafe?
I18nStore is type-safe by default. So, basically, you can't add the translation data that is not defined in the locale Json files. However, for fast development, you can off the typeSafe option manually.

// typeSafe: false
const YourComponent = () => {
  // useTranslation(sheetTitle: string)
  const { t } = useTranslation('header');

  return (
    <div>
      {/* t(key: string): any */}
      <button>{t('login')}</button>
    </div>
  );
};

2. Create i18n Context

import { i18nStore } from './file-path-of-i18nStore-initiated';
import { createI18nContext } from '@sheet-i18n/react';

export const { IntlProvider, useTranslation } = createI18nContext(i18nStore);

3. Mount Intl Context Provider in your App

import React from 'react';
import { IntlProvider } from './i18nContext';

const App = () => {
  return (
    <IntlProvider>
      <YourComponent />
    </IntlProvider>
  );
};

4. Use Translations

import React from 'react';
import { useTranslation } from './i18nContext';

const YourComponent = () => {
  const { t } = useTranslation('header');

  return (
    <div>
      <button>{t('login')}</button>
      <button>{t('logout')}</button>
    </div>
  );
};

Follow the documentation for @sheet-i18n/react to ensure proper configuration.

Base workflow

Install the CLI tool globally or as a dev dependency:

npm install -g @sheet-i18n/cli

or

npm install --save-dev @sheet-i18n/cli

Initialize the CLI in your project:

npx sheet-i18n init

After initialization, the "sheet.config.json" file will be created in the root of your project (and .gitignored automatically).

Configuration ⚙️

The CLI requires a sheet.config.json file in the root of your project. Run sheet-i18n init to generate this file automatically.

Example sheet.config.json:

{
  "watchEntry": "src",
  "detectExtensions": ["tsx", "ts", "jsx", "js"],

  "googleSheetConfig": {
    "credentials": {
      "sheetId": "YOUR_GOOGLE_SHEET_ID",
      "clientEmail": "YOUR_CLIENT_EMAIL",
      "privateKey": "YOUR_PRIVATE_KEY"
    },
    "defaultLocale": "en",
    "supportedLocales": ["en", "fr", "es"],
    "ignoredSheets": ["BASE"],
    "exportPath": "./src/locales"
  }
}

1. File change monitoring configuration

  • watchEntry (optional): Entry path to detect file changes relative to current working directory (default: src)
  • detectExtensions (optional): File extensions to monitor (default: jsx, js, tsx, ts).

2. Register command configuration

  • googleSheetConfig (required): Configuration for Google Sheets integration:
    • spreadsheetId (required): The ID of your Google Spreadsheet.
    • credentials (required): Contains sheetId, clientEmail, and privateKey for API authentication.
    • defaultLocale (required): Default language/locale used in the sheet header.
    • supportedLocales(required): List of locales supported in your sheet (default: [defaultLocale]).
    • headerStartRowNumber (optional): Row number where headers start (default: 1).
    • ignoredSheets (optional): Titles of sheets to exclude from the translation process.
    • exportPath (optional): Directory path to save exported translations based on the current working directory (default: .).

Commands

🎬 init

npx sheet-i18n init

Sets up the sheet.config.json file in your project. This configuration file is required for all other commands.


👀 watch

npx sheet-i18n watch

Monitors files or directories for changes and logs relevant updates. When watch mode is started, the CLI will detect changes of "useTranslation" and "t" calls of "@sheet-i18n/react" package.

//translationContext.tsx
import { createI18nContext } from 'sheet-i18n/react';

export const { IntlProvider, useTranslation } = createI18nContext(i18nStore);


// Component.tsx
import { useTranslation } from '../translationContext'

...

function Component (){
  // The arguments of useTranslation function = sheetTitle
  const { t } = useTranslation('environment');
  ...

  // The arguments of t function = translation key
  return (
      <>
          <SettingItem label={t('over')}>
          <SettingItem label={t('under')}>
      </>
  )
}

The watch result is

📝 Translations Store:
 {
  environment: Set(1) { 'over', 'under' }
 }

📤 register

sheet-i18n register [options]

Registers translation data to Google Sheets.

Remarkable features:

  1. The register command collects the current sheets in Google Spreadsheets. If there are sheets in your local changes that do not exist in the current list, it prompts you to create the missing sheets.

  2. It updates rows and adds "translation" entries using the GOOGLETRANSLATE function supported by Google Spreadsheets for automated translations.

  3. After registering, it asks whether you want to update the locale JSON data locally. It then exports the JSON data to the exportPath specified in sheet.config.json (default is the current working directory).

Options:

  • -s, --scope <scope>
    Define the scope of the registration process:
    • diff: Only scans translation keys that have been modified in the Git history (based on git diff).
    • total: Scans the entire directory for all translation keys and updates the spreadsheet, regardless of Git changes.
      Default: diff

Detailed description of the scope option:

Scope: diff
  • The CLI identifies changes in translation keys by comparing the current state of the codebase with the latest Git commit.
  • It only processes translation keys added, removed, or modified since the last commit.
  • This is useful for incremental updates, ensuring only new or updated keys are registered.
Example:
# diff is the default scope. So you can omit the --scope option.
npx sheet-i18n register

Scope: total
  • The CLI scans the entire specified directory for all translation keys from the directory path you provide.
  • This is useful for full synchronization, ensuring all keys are registered in the spreadsheet.
  • However, it may take longer to process large directories. So, use with caution.
Example:
sheet-i18n register --scope total

📄 export

npx sheet-i18n export

Exports translation data from Google Sheets to local export directory. The configuration of export command is based on sheet.config.json on your root.

{
  "googleSheetConfig": {
    "credentials": {
      "sheetId": "YOUR_GOOGLE_SHEET_ID",
      "clientEmail": "YOUR_CLIENT_EMAIL",
      "privateKey": "YOUR_PRIVATE_KEY"
    },
    "defaultLocale": "The base language of your application in sheet header",
    "ignoredSheets": ["BASE"],
    "exportPath": "The path of export directory of translation data. (default: current working directory)"
  }
}

License 📜

This project is licensed under the ISC License. See the LICENSE file for details.

Author ✍️

Created by devAnderson.