Skip to content

Repository files navigation

okTurtles Strings

Write your UI text right where it shows up. Translate it later in simple text files.

Most i18n libraries make you invent a key like nav.logout, put the text in en.json, and write t('nav.logout') in your template. Every string lives in two places, and your templates show keys instead of words.

With okTurtles' Strings, you write the text where it normally goes:

<button><i18n>Logout</i18n></button>
alert(L('Your changes were saved.'))

Run the strings extractor. It reads JavaScript and Flow (.js), TypeScript (.ts), Vue with HTML or Pug templates (.vue), HTML, Pug, and Astro files. It writes every string into one .strings file per language. To translate, fill in the right side:

/* components/NavBar.vue */
"Logout" = "Déconnexion";

No keys to invent. No build plugin. Less than 1 KB minified and gzipped.

This package is the part that runs in your app: L() and LTags() for any JavaScript or TypeScript code, and <i18n> components for Vue 3, Vue 2, and Astro.

How it compares

Strings i18next next-intl vue-i18n react-intl Lingui Paraglide JS
Write UI text where it is shown ✅ ❌ ❌ ❌ ✅ ✅ ❌
No keys or IDs to invent ✅ ❌ ❌ ❌ ✅ ✅ ❌
No compiler, macro, or bundler plugin ✅ ✅ ❌ ✅ ❌ ❌ ❌
Zero runtime dependencies ✅ ✅ ❌ ❌ ❌ ❌ ✅
Official Vue 3 support ✅ ✅ ❌ ✅ ✅ ✅ ✅
Official Vue 2 support ✅ ❌ ❌ ❌ ❌ ❌ ❌
Official Astro support ✅ ✅ ❌ ❌ ❌ ❌ ✅
Extractor updates every language's file ✅ ✅ ❌ ❌ ❌ ✅ ❌
Translation files show where each string is used ✅ ❌ ❌ ❌ ❌ ✅ ❌
Extracts from TypeScript ✅ ✅ ❌ ❌ ✅ ✅ ❌
Extracts from Flow ✅ ❌ ❌ ❌ ❌ ✅ ❌
Extracts from Vue HTML templates ✅ ❌ ❌ ❌ ✅ ✅ ❌
Extracts from Vue Pug templates ✅ ❌ ❌ ❌ ❌ ❌ ❌
Extracts from Astro files ✅ ✅ ❌ ❌ ❌ ❌ ❌
Extracts from plain HTML and Pug files ✅ ❌ ❌ ❌ ❌ ❌ ❌

Checked on November 30, 2026

Install

npm install @okturtles/strings

The package is ESM only. Each framework has its own entry, and each entry also exports everything from the core:

Import Contents Needs
@okturtles/strings L, LTags, language loading nothing
@okturtles/strings/vue Vue 3 <i18n>, StringsPlugin, useL, LKey Vue 3
@okturtles/strings/vue2 Vue 2 <i18n>, StringsPlugin Vue 2.6 or 2.7 (the full build for compile)
@okturtles/strings/astro Astro <I18n> Astro

Tested with Vue 3.5, Vue 2.6 and 2.7, and Astro 7.

The strings workflow

  1. Mark the English text: L('Logout') in .js/.ts, <i18n>Logout</i18n> in Vue templates (HTML or Pug), and <I18n>Logout</I18n> in .astro files.
  2. Run the extractor (for example ./strings.linux src/). It writes strings/english.strings and strings/english.json.
  3. Copy english.strings to (for example) french.strings, and translate the right side of each line. The next run of the extractor writes strings/french.json, a flat { "English text": "translation" } object.
  4. Give the library one loader for each <language>.json. L() and <i18n> then show the translation.

The extractor reads source code, not running code. So follow these rules, or the text is not extracted:

  • Call L by that exact name, with a string literal as the first argument. L(message), L(`...`), and this.L('...') are not extracted.
  • In .js files and in Vue <script> blocks without lang="ts", keep L('...') calls out of a script that has a top-level await. The extractor (version 2.3.2) cannot parse such a script: it reports a syntax error and extracts no L('...') string from it. It parses TypeScript correctly.
  • In Vue templates, write the lowercase <i18n>, and keep one root element: the extractor (version 2.3.2) cannot parse a template with several root elements.
  • In .astro files, import the component as I18n. Add is:raw when the text contains {placeholders}, so that Astro does not evaluate them.
  • The text prop of the components is not extracted. Put the text between the tags.

Core: @okturtles/strings

import { L, LTags, setLanguage, setTranslationLoaders } from '@okturtles/strings'

setTranslationLoaders({
  fr: () => import('./strings/french.json').then(module => module.default),
  'pt-BR': () => fetch('/strings/br-portuguese.json').then(response => response.json())
})

setLanguage(navigator.language).then(() => { // 'fr-CA' uses the 'fr' loader
  L('Logout') // 'Déconnexion'
  L('Hello {name}!', { name: 'Ana' }) // 'Bonjour Ana !' (a non-breaking space before '!')
  L('Read {a_}the FAQ{_a}.', { ...LTags('a'), a_: '<a href="/faq">' }) // 'Lisez <a href="/faq">la FAQ</a>.'
})
Export What it does
L(key, args?) Translates key into the current language.
setTranslationLoaders(loaders) Sets the loaders: { [languageTag]: () => Promise<table> }. It replaces the previous loaders. Tables that are already loaded stay loaded.
setLanguage(lang) Loads the table for lang, then makes it the language of L. If the loader fails, the promise rejects and the previous language stays. If calls overlap, the last call wins.
loadTranslationTable(lang) Loads the table for lang, but does not change the language of L.
useTranslation(lang?) Returns a translate function for lang, for code that renders many languages at once (server rendering). It does not load anything: load the table first. Without lang, it returns L.
LTags(...tags) Returns { br_: '<br/>' } plus { tag_: '<tag>', _tag: '</tag>' } for each tag.
template(string, ...args) Fills the placeholders of string (step 3 below).

Types: TranslationTable, TranslationArgs, TranslationFn, TranslationLoader.

How a language tag finds its loader: first a case-insensitive match on the loader key, then a match on the first part of the tag (fr-CA → fr). A language without a loader (English, for example) shows the English text as it is, and loads nothing. Each table loads only once: callers that ask at the same time share one load. A loader can return null or undefined for an empty table.

L() is not reactive: Vue and other frameworks do not render again when the language changes. Set the language before the app renders.

How a key is translated

  1. The key is looked up in the table as it is written. The extractor writes L('...') strings as they are, so L('Total: ') finds the key "Total: ".
  2. If that fails, the key is looked up again without its trailing whitespace and without the spaces and tabs after each newline. A missing or empty translation gives the English key as it is written.
  3. Placeholders are filled. {name} takes args.name; {0} takes args[0] (with an array, or with template('{0}', 'a')). A missing, null, or undefined value gives ''. Only the object's own properties are used. {{name}} gives the text {name}. This step always runs, so L('Hi {name}') without args gives 'Hi '.
  4. A whitespace character before ;, :, ?, or ! becomes a non-breaking space (U+00A0), as French typography needs.

The components insert the translation as HTML. Translations come from your own files, but args values do not have to: escape user-provided values before you pass them in args. Only the Vue 2 plugin has a sanitize option.

Vue 3: @okturtles/strings/vue

import { createApp } from 'vue'
import { StringsPlugin, setLanguage, setTranslationLoaders } from '@okturtles/strings/vue'
import App from './App.vue'

setTranslationLoaders({ fr: () => import('../strings/french.json').then(module => module.default) })
await setLanguage(navigator.language)
createApp(App).use(StringsPlugin).mount('#app')
<template>
  <div>
    <i18n tag="h1" class="title">Welcome back!</i18n>
    <i18n :args="{ ...LTags('strong'), name }">Hello {strong_}{name}{_strong}!</i18n>
    <button>{{ L('Save') }}</button>
  </div>
</template>

<script setup>
import { useL } from '@okturtles/strings/vue'

const L = useL()
const name = 'Ana'
const tabs = [L('General'), L('Groups')]
</script>
  • app.use(StringsPlugin, { L? }) registers the I18n component (templates write <i18n>) and adds L and LTags to every template (typed for TypeScript). If you give L (for example useTranslation(locale)), it is also provided under LKey, so <i18n> and useL() use it. Without it, they use the core L.
  • <i18n> props: tag (default 'span'), text, args. Other attributes and listeners go on the rendered element. The translation is computed when the component renders and is inserted as HTML, not sanitized.
  • useL() returns the translate function provided under LKey, or the core L. Call it in setup().
  • To render several languages in one process (server rendering), give each app its own translate function: await loadTranslationTable(locale), then app.use(StringsPlugin, { L: useTranslation(locale) }).

Vue 2: @okturtles/strings/vue2

import Vue from 'vue/dist/vue.esm.js' // the full build, which `<i18n compile>` needs
import dompurify from 'dompurify'
import { StringsPlugin, setLanguage, setTranslationLoaders } from '@okturtles/strings/vue2'
import App from './App.vue'

setTranslationLoaders({ fr: () => fetch('/assets/strings/french.json').then(response => response.json()) })
Vue.use(StringsPlugin, {
  sanitize: (html) => dompurify.sanitize(html, { ADD_TAGS: ['router-link'], ADD_ATTR: ['to'] })
})
await setLanguage(navigator.language)
new Vue({ render: (h) => h(App) }).$mount('#app')
i18n Hello
i18n.title(tag='p' :args='{ ...LTags("strong"), name }') Hello {strong_}{name}{_strong}!
i18n(compile :args='{ r1: `<router-link to="/login">`, r2: "</router-link>" }') Go to {r1}login{r2} page.
  • Vue.use(StringsPlugin, { sanitize? }) sets Vue.prototype.L and Vue.prototype.LTags, and registers the functional <i18n> component. The package does not import vue: it uses the constructor that you give to Vue.use. Give it the root constructor, because compile uses its Vue.compile.
  • <i18n> props: tag (default 'span'), text, args, compile. sanitize (default: none) cleans each translation before it is inserted as HTML.
  • With compile, the translation is compiled as a Vue template, so it can contain components such as <router-link>. sanitize runs first, so it must allow those components and their attributes, as the example above does for router-link and to.
  • It adds rel="noopener noreferrer" to tag="a" with target="_blank", and it warns and shows the text as it is when the translation is empty.
  • In component scripts, import { L } from '@okturtles/strings' instead of calling this.L(), which the extractor does not read. This entry adds no TypeScript types for this.L.

Astro: @okturtles/strings/astro

Register the loaders and load the page's language in a middleware:

// src/middleware.ts
import { defineMiddleware } from 'astro:middleware'
import { loadTranslationTable, setTranslationLoaders } from '@okturtles/strings'

setTranslationLoaders({
  fr: () => import('../strings/french.json').then(module => module.default)
})

export const onRequest = defineMiddleware(async (context, next) => {
  const { locale } = context.params
  if (locale) {
    await loadTranslationTable(locale)
    context.locals.locale = locale
  }
  return next()
})
// src/env.d.ts
declare namespace App {
  interface Locals { locale?: string }
}
---
// src/pages/[locale]/index.astro
import I18n, { LTags, useTranslation } from '@okturtles/strings/astro'

export function getStaticPaths () {
  return ['en', 'fr'].map(locale => ({ params: { locale } }))
}

const L = useTranslation(Astro.locals.locale)
---
<h1>{L('Create a group')}</h1>
<I18n tag="p" class="subtitle">Welcome to our site</I18n>
<I18n is:raw tag="p" args={{ ...LTags('a'), a_: '<a href="/faq">' }}>
  Read {a_}the FAQ{_a}.
</I18n>
  • <I18n> props: tag (default 'span'), text, args, locale, class (and class:list). Other attributes go on the rendered element. The translation is inserted with set:html, not sanitized.
  • The language comes from the locale prop, then Astro.locals.locale, then Astro.currentLocale (Astro's i18n routing), then the language of L. The component does not load tables: load them first, in a middleware or with await loadTranslationTable(...) in the frontmatter.
  • The middleware and <I18n> must share one copy of the library, so Astro must bundle it. Astro does this when the package is in your package.json (npm install adds it). If it is not, the build fails with Unknown file extension ".astro"; then add vite: { resolve: { noExternal: ['@okturtles/strings'] } } to astro.config.mjs.
  • astro check types the <I18n> props. Keep skipLibCheck: true (Astro's tsconfig presets set it): plain tsc cannot resolve the .astro file that this package's type declarations import.
  • For Vue islands, use the @astrojs/vue appEntrypoint: find the page's language, then await loadTranslationTable(locale) and app.use(StringsPlugin, { L: useTranslation(locale) }).

Common setups

Register the loaders in one module

Register the loaders in one module, and import the library through that module everywhere else. Then every entry point (a page, a middleware, a client script) registers the loaders before it translates.

// src/i18n.js
import { setTranslationLoaders } from '@okturtles/strings'

export { L, LTags, loadTranslationTable, setLanguage, useTranslation } from '@okturtles/strings'

setTranslationLoaders({
  fr: () => import('../strings/french.json').then(module => module.default)
})

// src/home.js
import { L } from './i18n.js'

document.title = L('Home')
  • The extractor finds L('...') by the name L only, so the strings of a re-exported L are extracted.
  • A web worker or a service worker has its own copy of the library. Register the loaders and set the language there too.

Many languages, or tables from an API

Make the loaders from a map when there are many languages, or when a server sends the tables.

import { setTranslationLoaders } from '@okturtles/strings'

const files = { fr: 'french', es: 'spanish', 'pt-BR': 'br-portuguese' }

setTranslationLoaders(Object.fromEntries(
  Object.entries(files).map(([tag, file]) => [
    tag,
    () => fetch(`/strings/${file}.json`).then(response => response.json())
  ])
))
  • A loader gets no arguments, and it can call any API. It runs once for each loader key: setLanguage('fr-CA') and setLanguage('fr') share the fr table. After a failure, the next call runs the loader again.

Start the app when a table fails to load

setLanguage() rejects when the loader fails. Catch the error, so that the app still starts.

import { createApp } from 'vue'
import { StringsPlugin } from '@okturtles/strings/vue'
import { setLanguage } from './i18n.js'
import App from './App.vue'

try {
  await setLanguage(navigator.language)
} catch (error) {
  console.error(error)
}
createApp(App).use(StringsPlugin).mount('#app')
  • The previous language stays. At start, that is the English text.

Switch the language at run time

L() is not reactive. To show a new language, set it, then mount the app again.

import { createApp } from 'vue'
import { StringsPlugin } from '@okturtles/strings/vue'
import { setLanguage } from './i18n.js'
import App from './App.vue'

let app

function mountApp () {
  app = createApp(App).use(StringsPlugin)
  app.mount('#app')
}

export async function switchLanguage (lang) {
  await setLanguage(lang)
  app.unmount()
  mountApp()
}

await setLanguage(navigator.language)
mountApp()
  • If the table fails to load, switchLanguage() rejects and the app stays as it is.
  • The new app starts with new component state. To keep it, save the language (for example in localStorage) and reload the page instead.

Several languages in one server process

For code that writes text in the language of each user (emails, notifications), load the table, then translate with useTranslation().

import { loadTranslationTable, useTranslation } from './i18n.js'

export async function welcomeEmail (user) {
  await loadTranslationTable(user.language)
  const L = useTranslation(user.language)
  return {
    subject: L('Welcome!'),
    body: L('Hello {name}, your account is ready.', { name: user.name })
  }
}
  • Name the function L, so that the extractor finds the strings.
  • For Vue 3 server rendering and for Astro, see Vue 3 and Astro.

Flow

Flow does not read the exports field of package.json, and many .flowconfig files ignore node_modules. If Flow cannot find the package, declare each entry that you import in a library definition file (a file in the [libs] section of .flowconfig):

declare module '@okturtles/strings' { declare module.exports: any }
declare module '@okturtles/strings/vue2' { declare module.exports: any }

Tested with Flow 0.154.

Real-world Examples

Development

npm install
npm run build      # dist/: compiles src/ and copies I18n.astro
npm run typecheck
npm run lint
npm test           # node:test; the Astro test packs the package and builds test/fixtures/astro-site

Tests are TypeScript files that Node runs directly (developed with Node 24), so src/ uses only TypeScript syntax that Node can strip.

License

MIT

Releases

Sponsor this project

Packages

Contributors

Languages