auto-i18n-translation-plugins

repository·main·Indexed 20 days ago

https://github.com/auto-i18n/auto-i18n-translation-plugins

A frontend auto-translation plugin for JavaScript frameworks like Vue and React that enables multi-language support without source code changes. It integrates with build tools including webpack, vite, and rollup, and supports translation services such as Google Translate, Youdao, Baidu, and Volcengine AI, as well as custom translators. Version 1.1.16.

Tokens
35.9K
Snippets
131
Records
153
Agent score
65%

What's inside auto-i18n-translation-plugins

  1. Overview of auto-i18n-translation-plugins

    main

    The auto-i18n-translation-plugins is a frontend auto-translation plugin designed to provide multi-language support without requiring manual source code modifications. It works by detecting text that needs translation and using translation services to automate the process.

    Key Capabilities:

    • Zero Code Changes: Achieve multi-language support without modifying your existing source code.
    • Framework Agnostic: Supports all JavaScript-based frontend frameworks, including Vue 2, Vue 3, and React.
    • Build Tool Compatibility: Works with Webpack, Vite, Rsbuild, and Rollup.
    • Multiple Translation Engines: Includes default support for Google and Youdao translation services, with the ability to implement custom translators.
  2. Switching JSON storage modes

    main

    The languageJsonMode option allows you to choose between:

    • 'merged': All languages are combined into a single index.json.
    • 'split': Each language is stored in its own separate JSON file.

    Warning: When switching between these modes, you should set rewriteConfig: true to ensure the plugin regenerates the configuration files correctly and avoids conflicts between old and new file structures.

  3. Use deepScan for precise template translation

    main

    By default, the plugin scans entire strings or template literals. If a string contains a target language character, the whole block might be scanned, leading to inaccurate translations.

    Setting deepScan: true enables a more granular approach. When enabled, the plugin generates a global $deepScan function. You can wrap template strings with $deepScan to tell the plugin to split the string and only translate the specific parts that match the translation pattern.

    Note: $deepScan is a compile-time instruction. At runtime, it returns the original value without modification. It only works when deepScan: true is set in the configuration.

    // 1. Enable in config
    // { deepScan: true }
    
    // 2. Use in code to mark strings for deep scanning
    const template = $deepScan(`
        <div class="container">
            <h1 class="title">欢迎使用</h1>
            <p>这是一个测试</p>
        </div>
    `);
    
    // The plugin transforms the above at compile-time into:
    // const template = `<div class="container"><h1 class="title">${$t('欢迎使用')}</h1><p>${$t('这是一个测试')}</p></div>`;
  4. Configure translation modes: full-auto vs semi-auto

    main

    The translateType parameter determines how the plugin identifies text to translate:

    • full-auto (Default): The plugin automatically scans strings and template strings for text that needs translation.
    • semi-auto: The plugin only translates text that is explicitly wrapped in the translation function (e.g., $t('text')). This is useful when you want total control over what gets translated.
    // semi-auto usage example
    const HelloWorld = ({ name }) => {
        return (
            <div>
                <h1>{$t('Hello,')} {name}!</h1>
                <p>{$t('Welcome to our application')}</p>
            </div>
        )
    }
  5. Enable deep string scanning with `deepScan`

    main

    By default, if a template string contains any target language text, the plugin includes the entire string for translation. Enabling deepScan: true allows the plugin to split and reconstruct template strings, translating only the specific matching text segments.

    To use this, wrap your template strings with the $deepScan function. This tells the plugin at compile time that the string needs granular scanning.

    Note: $deepScan only returns the original value at runtime; its primary purpose is for the build-time plugin.

    // 1. Set deepScan: true in your plugin config
    // 2. Use $deepScan in your code
    const template = $deepScan(`
        <div class="container">
            <h1>Welcome</h1>
        </div>
    `)
    
    // The plugin converts this to:
    // const template = `<div class="container"><h1>${$t('Welcome')}</h1></div>`
  6. Choose between full-auto and semi-auto translation modes

    main

    The translateType option determines how the plugin identifies text for translation:

    • full-auto (Default): The plugin automatically scans the codebase. The source language support is limited to (Chinese), (Japanese), (Korean), and (Russian).
    • semi-auto: Supports all source languages. In this mode, you must explicitly wrap the target text using the function name specified in translateKey (e.g., $t('text')). This ensures the plugin knows exactly which strings to translate.
    // Example of semi-auto usage
    const HelloWorld = ({ name = 'World' }) => {
        return (
            <div className="hello-world">
                <h1>{$t('Hello,')} {name}!</h1>
                <p>{$t('Welcome to our application')}</p>
            </div>
        )
    }
  7. Run the Rsbuild React example project

    main

    Use the following commands to manage the development and production lifecycle of the Rsbuild React example:

    • Development: Start the dev server to view the app at http://localhost:3000.
    • Production Build: Build the application for production.
    • Preview: Locally preview the production build.
    # Start the dev server
    pnpm dev
    
    # Build the app for production
    pnpm build
    
    # Preview the production build locally
    pnpm preview
  8. Configure the plugin in Vite, Webpack, or Rsbuild

    main

    Add the plugin to your build configuration. You must provide a translator instance. The following examples demonstrate how to initialize the plugin with a YoudaoTranslator.

    // Vite Example (vite.config.js)
    import vitePluginsAutoI18n, { YoudaoTranslator } from 'vite-auto-i18n-plugin'
    import vue from '@vitejs/plugin-vue'
    import { defineConfig } from 'vite'
    
    export default defineConfig({
        plugins: [
            vue(),
            vitePluginsAutoI18n({
                translator: new YoudaoTranslator({
                    appId: 'YOUR_APP_ID',
                    appKey: 'YOUR_APP_KEY'
                })
            })
        ]
    })
    
    // Webpack Example (webpack.config.js)
    const webpackPluginsAutoI18n = require('webpack-auto-i18n-plugin')
    const { YoudaoTranslator } = require('webpack-auto-i18n-plugin')
    
    const i18nPlugin = new webpackPluginsAutoI18n.default({
        translator: new YoudaoTranslator({
            appId: 'YOUR_APP_ID',
            appKey: 'YOUR_APP_KEY'
        })
    })
    
    module.exports = {
        plugins: [
            i18nPlugin
        ]
    }
    
    // Rsbuild Example (rsbuild.config.js)
    const rsbuildPluginsAutoI18n = require('rsbuild-auto-i18n-plugin')
    const { YoudaoTranslator } = require('rsbuild-auto-i18n-plugin')
    
    export default defineConfig({
      plugins: [
        rsbuildPluginsAutoI18n({
          targetLangList: ['en'],
          translator: new YoudaoTranslator({
                appId: 'YOUR_APP_ID',
                appKey: 'YOUR_APP_KEY'
            })
        })
      ],
    });
  9. Switch languages in your application

    main

    The plugin provides two ways to switch languages:

    1. Basic Switch (Requires Page Reload)

    Update localStorage and reload the window. The value must be a key from the langMap (found in lang/index.js).

    window.localStorage.setItem('lang', 'en')
    window.location.reload()

    2. Instant Switch (No Reload)

    Use window.$changeLang(lang) to change the language immediately. In frameworks like Vue, you may need to trigger a re-render of the component tree to reflect changes.

    window.$changeLang('en')

    3. Replace Language Packs Manually

    You can overwrite the global window.langMap object to modify the content of the generated language files at runtime.

    window.langMap = {
        en: { key: 'hello' },
        'zh-cn': { key: '你好' }
    }
    // Then call $changeLang to apply
    window.$changeLang('en')
    /* Vue Example for Instant Switch */
    <template>
        <button @click="changeLang('en')">English</button>
        <button @click="changeLang('zh-cn')">中文</button>
    </template>
    
    <script>
    export default {
        methods: {
            changeLang(lang) {
                window.$changeLang(lang)
                this.isShow = false
                this.$nextTick(() => {
                    this.isShow = true
                })
            }
        }
    }
    </script>