百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
S

simple-translator

> 编程语言
开源

使用纯 JavaScript 实现简单、通用的翻译。

100 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

使用纯 JavaScript 实现简单、通用的翻译。

Simple Translator

Simple, client-side translation with pure JavaScript.

Table of Contents

  • The problem
  • The solution
  • Installation
    • In the browser
    • Using Node.js or bundlers
  • Examples
    • Translate HTML in the browser
    • Translate single strings
    • Fetch JSON from the server
  • Usage
    • Translating HTML content
    • Translating HTML attributes
    • Translating programmatically
  • Configuration
  • API reference
    • new Translator(options)
    • instance
      • translateForKey(key, language)
      • translatePageTo(language)
      • add(language, translation)
      • remove(language)
      • fetch(languageFiles, save)
      • get currentLanguage
  • Browser support
  • Issues

The problem

You want to make your website available in multiple languages. You perhaps already looked for solutions out there and discovered various services and libraries, and dozens of other smaller packages that offer more or less what you are looking for.

Some of them might be too grand for your purpose. You don't want to install a 100 KB dependency just for a simple translation. Or, perhaps you've found smaller libraries but are missing essential features.

The solution

Simple Translator is a very lightweight (~9 KB minified) solution for translating content with pure JavaScript. It works natively in the browser and Node.js.

  • Translate single strings
  • Translate entire HTML pages
  • Easily fetch JSON resource files (containing your translations)
  • Make use of global helper functions
  • Detect the user's preferred language automatically

Installation

In the browser

A UMD build is available via unpkg. Just paste the following link into your HTML, and you're good to go:

xml

Using Node.js or bundlers

This package is distributed via npm. It's best to install it as one of your project's dependencies:

bash
npm i @andreasremdt/simple-translator

Or using yarn:

bash
yarn add @andreasremdt/simple-translator

Examples

Want to see the bigger picture? Check out the live demos at CodeSandbox and see how you can integrate the library with popular frameworks or in pure JavaScript:

  • Vanilla JavaScript
  • React
  • Vue.js
  • Lit-Element (Web Components) currently in progress

Translate HTML in the browser

xml

  
Translate me

  
This subtitle is getting translated as well

Translate single strings

…

Fetch JSON from the server

i18n/de.json:

json
"header": {
  "title": "Eine Überschrift",
  "subtitle": "Dieser Untertitel ist nur für Demozwecke",
}

i18n/en.json:

json
"header": {
  "title": "Some Nice Title",
  "subtitle": "This Subtitle is Going to Look Good",
}

index.js:

javascript
import Translator from '@andreasremdt/simple-translator';

// The option `filesLocation` is "/i18n" by default, but you can
// override it
var translator = new Translator({
  filesLocation: '/i18n',
});

// This will fetch "/i18n/de.json" and "/i18n/en.json"
translator.fetch(['de', 'en']).then(() => {
  // You now have both languages available to you
  translator.translatePageTo('de');
});

Usage

Simple Translator can be used to translate entire websites or programmatically via the API in the browser or Node.js.

Translating HTML content

Note that this feature is only available in a browser environment and will throw an error in Node.js.

In your HTML, add the data-i18n attribute to all DOM nodes that you want to translate. The attribute holds the key to your translation in dot syntax as if you were accessing a JavaScript object. The key resembles the structure of your translation files.

xml

  
Headline

Some introduction content

Import and initialize the translator into your project's source code. The constructor accepts an optional object as configuration.

javascript
import Translator from '@andreasremdt/simple-translator';

var translator = new Translator();

Next, you need to register the translation sources. Each language has its own source and must be made available to the translator. You can either fetch them from the server or directly pass them as a JavaScript object:

javascript
// By using `fetch`, you load the translation sources asynchronously
// from a directory in your project's folder. The resources must
// be in JSON. After they are fetched, you can use the API to
// translate the page.
translator.fetch(['en', 'de']).then(() => {
  // -> Translations are ready...
  translator.translatePageTo('en');
});

// By using `add`, you pass the translation sources directly
// as JavaScript objects and then use the API either through
// chaining or by using the `translator` instance again.
translator.add('de', jsonObject).translatePageTo('de');

Each translation source consists of a key (the language itself, formatted in the ISO-639-1 language code) and an object, holding key-value pairs with the translated content.

Using the example above, the translation sources for each language must have the following structure:

javascript
{
  "header": {
    "title": "Translated title"
  },
  "intro": "The translated intro"
}

When fetching the JSON files using fetch(), the translator looks for a folder called i18n in the root of your web server. You can configure the path in the configuration.

When a language has been registered and is ready, you can call translatePageTo() and provide an optional parameter for the target language, such as "en".

javascript
translator.translatePageTo(); // Uses the default language
translator.translatePageTo('de'); // Uses German

Translating HTML attributes

You can translate the text content of a DOM element (it's innerHTML) or any other attribute, such as title or placeholder. For that, pass data-i18n-attr and a space-separated list of attributes to the target DOM node:

xml

Be careful to have the same amount of keys and attributes in data-i18n and data-i18n-attr. If you want to translate both placeholder and title, you need to pass two translation keys for it to work.

By default, if data-i18n-attr is not defined, the innerHTML will be translated.

Translating programmatically

Instead of translating the entire page or some DOM nodes, you can translate a single, given key via translateForKey(). The first argument should be a key from your translation sources, such as "header.title", and the second argument should be the target language like "en" or "de". Note that the language must have been registered before calling this method.

javascript
translator.add('de', jsonObject);

console.log(translator.translateForKey('header.title', 'de'));
// -> prints the translation

By default, Simple Translator registers a global helper on the window object to help you achieve the same without having to write the method name.

javascript
__.('header.title', 'de');

You can change the name of this helper in the configuration.

Configuration

When initializing the Translator class, you can pass an object for configuration. By default, the following values apply:

javascript
var translator = new Translator({
  defaultLanguage: 'en',
  detectLanguage: true,
  selector: '[data-i18n]',
  debug: false,
  registerGlobally: '__',
  persist: false,
  persistKey: 'preferred_language',
  filesLocation: '/i18n',
});
Key Type Default Description
defaultLanguage String 'en' The default language, in case nothing else has been specified.
detectLanguage Boolean true If set to true, it tries to determine the user's desired language based on the browser settings.
selector String '[data-i18n]' Elements that match this selector will be translated. It can be any valid element selector.
debug Boolean false When set to true, helpful logs will be printed to the console. Valuable for debugging and problem-solving.
registerGlobally String,Boolean '__' When set to a String, it will create a global helper with the same name. When set to false, it won't register anything.
persist Boolean false When set to true, the last language that was used is saved to localStorage.
persistKey String 'preferred_language' Only valid when persist is set to true. This is the name of the key with which the last used language is stored in localStorage.
filesLocation String '/i18n' The absolute path (from your project's root) to your localization files.

API reference

new Translator(Object?: options)

Creates a new instance of the translator. You can define multiple instances, although this should not be a use-case.

Only accepts one parameter, a JavaScript Object, with a custom config.

javascript
import Translator from '@andreasremdt/simple-translator';

var translator = new Translator();
// or...
var translator = new Translator({
  ...
});

translateForKey(String: key, String?: language)

Translates a single translation string into the desired language. If no second language parameter is provided, then:

  • It utilizes the last used language (accessible via the getter currentLanguage, but only after calling translatePageTo() at least once.
  • If no previously used language was set and the detectLanguage option is enabled, it u

Issues· 11 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

JavaScripti18njavascriptlanguagetranslator

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言