npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

vue-auto-i18n-plus

v1.3.3

Published

Vue.js automatic internationalization plugin with auto-marking and translation file generation

Downloads

112

Readme

vue-auto-i18n-plus

Vue.js 自动国际化插件,支持自动标记文本节点和生成翻译文件,兼容Vue 2 和 Vue 3。

🌟 特性

  • 自动标记:无需手动添加 property 属性,自动识别需要翻译的文本
  • 智能生成:自动生成可读性强的翻译键名
  • 多语言支持:支持中英文等多种语言的自动识别和处理
  • 性能优化:支持批处理、防抖等性能优化策略
  • 浏览器兼容:兼容现代浏览器,对老旧浏览器提供降级处理
  • 配置灵活:丰富的配置选项,支持自定义处理规则

📚 API 参考

translateComponent(vNode, vm, content, bigJson, options)

主要的翻译处理函数,用于处理单个Vue组件的国际化

参数:

  • vNode: Vue 虚拟DOM节点
  • vm: Vue实例
  • content: 上下文内容(支持多种扩展功能)
  • bigJson: 多语言数据对象
  • options: 配置选项

返回值:

  • 无返回值,直接修改组件中的文本内容

batchGenerateTranslations(components, outputDir, languages)

批量生成翻译文件,用于在构建时自动生成翻译资源文件

参数:

  • components: 需要处理的组件列表
  • outputDir: 输出目录
  • languages: 支持的语言列表

返回值:

  • Promise: 包含处理结果的Promise对象

getPropertyMapping()

获取自动生成的键名映射关系

返回值:

  • Object: 键名与原始文本的映射关系对象

📦 安装

npm install vue-auto-i18n-plus --save

🚀 快速开始

基本使用

// main.js
import { translateComponent } from 'vue-auto-i18n-plus'

// 准备多语言数据
const languageData = {
  'auto_欢迎使用系统': {
    'zh': '欢迎使用系统',
    'en': 'Welcome to System',
    'ja': 'システムへようこそ'
  }
}

// 在 Vue 组件中使用
export default {
  mounted() {
    translateComponent(this._vnode, this, null, languageData)
  }
}

自动标记模式(推荐)

<template>
  <!-- 无需手动添加 property,插件会自动识别文本内容 -->
  <div>欢迎使用系统</div>
  <button>登录</button>
  <p>这是一个自动翻译的段落</p>
  <span>当前用户: {{ userName }}</span>
</template>

手动标记模式

<template>
  <!-- 为需要多语言的元素添加 property 属性 -->
  <div property="welcome.message">欢迎使用系统</div>
  <button property="login.button">登录</button>
  
  <!-- 使用 proValue 属性指定数据路径 -->
  <span property="user.greeting" proValue="userInfo.name">欢迎, {{ userInfo.name }}</span>
</template>

在页面中使用 vue-auto-i18n-plus 进行翻译非常简单,以下是具体的使用方法:

🚀 页面内翻译使用方法

1. 基本使用方式

// 在你的Vue组件中
import { translateComponent } from 'vue-auto-i18n-plus'

export default {
  name: 'MyPage',
  mounted() {
    // 准备翻译数据
    const translations = {
      'auto_欢迎使用系统': 'Welcome to System',
      'auto_登录': 'Login',
      'auto_注册': 'Register'
    }
    
    // 执行翻译
    translateComponent(this._vnode, this, null, translations)
  }
}

2. 结合语言切换功能

import { translateComponent } from 'vue-auto-i18n-plus'

export default {
  name: 'MyPage',
  data() {
    return {
      currentLanguage: 'zh' // 当前语言
    }
  },
  mounted() {
    this.loadTranslations()
  },
  methods: {
    async loadTranslations() {
      // 根据当前语言加载对应翻译文件
      const translations = await import(`@/locales/${this.currentLanguage}.json`)
      translateComponent(this._vnode, this, null, translations.default)
    },
    
    async switchLanguage(lang) {
      this.currentLanguage = lang
      await this.loadTranslations()
    }
  }
}

3. 自动标记模式(推荐)

在你的Vue模板中,无需做任何特殊处理:

<template>
  <div class="container">
    <h1>欢迎使用系统</h1>
    <p>这是一个自动翻译的段落</p>
    <button>登录</button>
    <button>注册</button>
    <div>当前用户: {{ username }}</div>
  </div>
</template>

<script>
import { translateComponent } from 'vue-auto-i18n-plus'

export default {
  name: 'HomePage',
  data() {
    return {
      username: '张三'
    }
  },
  mounted() {
    // 插件会自动识别并翻译模板中的文本
    const translations = {
      'auto_欢迎使用系统': 'Welcome to System',
      'auto_这是一个自动翻译的段落': 'This is an auto-translated paragraph',
      'auto_登录': 'Login',
      'auto_注册': 'Register',
      'auto_当前用户': 'Current User'
    }
    
    translateComponent(this._vnode, this, null, translations)
  }
}
</script>

4. 手动标记模式

如果需要更精确的控制,可以手动添加 property 属性:

<template>
  <div class="container">
    <h1 property="welcome.title">欢迎使用系统</h1>
    <p property="welcome.description">这是一个自动翻译的段落</p>
    <button property="auth.login">登录</button>
    <button property="auth.register">注册</button>
    <div property="user.info" proValue="username">当前用户: {{ username }}</div>
  </div>
</template>

<script>
import { translateComponent } from 'vue-auto-i18n-plus'

export default {
  name: 'HomePage',
  data() {
    return {
      username: '张三'
    }
  },
  mounted() {
    const translations = {
      'welcome.title': 'Welcome to System',
      'welcome.description': 'This is an auto-translated paragraph',
      'auth.login': 'Login',
      'auth.register': 'Register',
      'user.info': 'Current User'
    }
    
    translateComponent(this._vnode, this, null, translations)
  }
}
</script>

5. 配置选项使用

import { translateComponent, defaultOptions } from 'vue-auto-i18n-plus'

export default {
  mounted() {
    const translations = {
      // 你的翻译数据
    }
    
    // 自定义配置
    const options = {
      ...defaultOptions,
      autoMark: true,           // 启用自动标记
      excludeClasses: ['no-translate', 'ignore-i18n'], // 排除特定类名
      debugMode: false,         // 生产环境关闭调试
      batchSize: 30             // 调整批处理大小
    }
    
    translateComponent(this._vnode, this, null, translations, options)
  }
}

📁 翻译文件结构

你需要准备类似这样的翻译文件:

// locales/zh.json (中文)
{
  "auto_欢迎使用系统": "欢迎使用系统",
  "auto_登录": "登录",
  "auto_注册": "注册"
}

// locales/en.json (英文)
{
  "auto_欢迎使用系统": "Welcome to System",
  "auto_登录": "Login",
  "auto_注册": "Register"
}

🔄 实时语言切换

export default {
  data() {
    return {
      currentLang: 'zh'
    }
  },
  methods: {
    changeLanguage(lang) {
      this.currentLang = lang
      this.applyTranslations()
    },
    
    applyTranslations() {
      import(`@/locales/${this.currentLang}.json`).then(translations => {
        translateComponent(this._vnode, this, null, translations.default)
      })
    }
  },
  
  mounted() {
    this.applyTranslations()
  }
}

这样就可以在页面中实现国际化翻译功能了!插件会自动处理文本替换,你只需要提供对应的翻译数据即可。

⚙️ 配置选项

基本配置选项

const options = {
  autoMark: true,                    // 启用自动标记
  excludeTags: ['SCRIPT', 'STYLE'],   // 排除的标签
  excludeClasses: ['no-translate'],   // 排除的类名
  minTextLength: 2,                  // 最小文本长度
  maxTextLength: 500,                // 最大文本长度
  propertyPrefix: 'auto_'            // property 前缀
}

高级配置选项

const advancedOptions = {
  debugMode: false,                  // 调试模式
  showOriginalText: false,           // 是否显示原始文本
  translationStrategy: 'eager',      // 翻译策略: 'eager' | 'lazy' | 'ondemand'
  updateStrategy: 'merge',           // 更新策略: 'merge' | 'overwrite' | 'skip'
  batchSize: 50,                     // 批处理大小
  throttleDelay: 100,                // 节流延迟(ms)
  conditionRenderSupport: true,      // 支持条件渲染内容
  dynamicContentHandling: 'observe'  // 动态内容处理: 'observe' | 'poll' | 'manual'
}

默认配置说明

const defaultOptions = {
  autoMark: true,
  excludeTags: ['SCRIPT', 'STYLE', 'META', 'LINK'],
  excludeClasses: ['no-translate', 'ignore-i18n'],
  minTextLength: 1,
  maxTextLength: 1000,
  processComponentProps: true,
  isTranslatable: null,
  propertyPrefix: 'auto_',
  debugMode: false,
  showOriginalText: false,
  translationStrategy: 'eager',
  updateStrategy: 'merge',
  dynamicContentHandling: 'observe',
  conditionRenderSupport: true,
  batchSize: 50,
  throttleDelay: 100
}

📁 批量生成翻译文件

生成翻译文件

import { batchGenerateTranslations } from 'vue-auto-i18n-plus'

// 定义需要处理的组件列表
const componentsToProcess = [
  { vNode: homeComponent._vnode, vm: homeComponent, name: 'Home' },
  { vNode: userProfileComponent._vnode, vm: userProfileComponent, name: 'UserProfile' }
]

// 生成翻译文件
batchGenerateTranslations(
  componentsToProcess,
  './src/locales',  // 输出目录
  ['zh', 'en', 'ja'] // 支持的语言
).then(result => {
  console.log('翻译文件生成完成:', result)
})

生成的文件结构

src/locales/
├── zh.json          # 中文翻译文件
├── en.json          # 英文翻译文件
├── ja.json          # 日文翻译文件
└── mapping.json     # 映射关系参考文件

批量生成翻译文件与手动标记结合使用

1. 翻译文件准确性问题

  • 自动生成的局限性

    • 自动生成的翻译键名可能不够语义化
    • 无法识别动态数据绑定的内容
    • 可能遗漏某些需要翻译的文本
  • 翻译质量控制

    • 生成的翻译文件只包含原始文本,需要人工翻译目标语言内容
    • 建议结合专业翻译人员进行校对

2. 结合手动标记的策略

自动+手动混合标记模式:

<template>
  <!-- 自动标记:纯文本内容 -->
  <h1>欢迎使用系统</h1>
  <p>这是一个介绍段落</p>
  
  <!-- 手动标记:需要指定数据源或特殊处理的内容 -->
  <div property="user.greeting" proValue="userName">
    欢迎, {{ userName }}
  </div>
  
  <!-- 手动标记:复杂表达式 -->
  <span property="order.status" proValue="order.statusText">
    订单状态: {{ order.statusText }}
  </span>
</template>

分层处理策略:

  1. 第一层:批量生成基础翻译文件

    // 使用 batchGenerateTranslations 生成基础文件
    batchGenerateTranslations(components, './locales', ['zh', 'en'])
  2. 第二层:手动补充和修正

    // 补充手动标记的翻译内容
    const manualTranslations = {
      'user.greeting': 'Welcome, {userName}',
      'order.status': 'Order Status: {status}'
    }
  3. 第三层:翻译文件合并

    // 合并自动生成和手动添加的翻译内容
    const finalTranslations = Object.assign(autoTranslations, manualTranslations)

3. 最佳实践建议

  • 优先使用自动标记:处理静态文本内容
  • 手动标记补充:处理动态数据和特殊场景
  • 定期更新:当组件内容变化时重新生成翻译文件
  • 建立规范:制定团队内部的翻译键命名规范
  • 质量检查:结合人工校对确保翻译准确性

🔧 content 参数功能扩展

1. 上下文数据传递

const contextData = {
  componentName: 'UserProfile',
  route: '/user/profile',
  locale: 'zh-CN'
};
translateComponent(vNode, vm, contextData, bigJson, options);

2. 作用域翻译内容

const scopeContent = {
  scope: 'user.profile',
  translations: {
    'title': '用户资料',
    'edit': '编辑'
  }
};
translateComponent(vNode, vm, scopeContent, bigJson, options);

3. 动态内容注入

const dynamicContent = {
  variables: {
    userName: '张三',
    userId: '12345'
  }
};
translateComponent(vNode, vm, dynamicContent, bigJson, options);

4. 配置覆盖

const configContent = {
  overrideOptions: {
    excludeClasses: ['profile-section'],
    minTextLength: 3
  }
};
translateComponent(vNode, vm, configContent, bigJson, options);

🛠️ 高级使用场景

1. Vue 2 项目集成

// main.js
import Vue from 'vue'
import { translateComponent, defaultOptions } from 'vue-auto-i18n-plus'

// 创建翻译插件
const i18nPlugin = {
  install(Vue) {
    Vue.mixin({
      mounted() {
        if (this._vnode) {
          // 加载对应语言的翻译文件
          const languageData = require(`@/locales/${this.$i18n.locale}.json`)
          translateComponent(this._vnode, this, null, languageData, defaultOptions)
        }
      }
    })
  }
}

Vue.use(i18nPlugin)

2. Vue 3 项目集成

// main.js
import { createApp } from 'vue'
import { translateComponent, defaultOptions } from 'vue-auto-i18n-plus'

const app = createApp(App)

app.mixin({
  mounted() {
    if (this._) {
      // 加载对应语言的翻译文件
      const languageData = require(`@/locales/${this.$i18n.locale}.json`)
      translateComponent(this._, this, null, languageData, defaultOptions)
    }
  }
})

app.mount('#app')

3. 结合 Vue I18n 使用

import { createI18n } from 'vue-i18n'
import { translateComponent } from 'vue-auto-i18n-plus'

const i18n = createI18n({
  locale: 'zh',
  messages: {
    zh: require('@/locales/zh.json'),
    en: require('@/locales/en.json')
  }
})

// 在组件中使用
export default {
  mixins: [i18n],
  mounted() {
    translateComponent(
      this._vnode, 
      this, 
      null, 
      this.$i18n.messages[this.$i18n.locale], 
      { autoMark: true }
    )
  }
}

4. 构建时自动生成翻译文件

// build-i18n.js
const { batchGenerateTranslations } = require('vue-auto-i18n-plus')
const path = require('path')

// 模拟组件数据(实际项目中需要从Vue应用中提取)
const components = [
  {
    vNode: mockVNode1,
    vm: mockVM1,
    name: 'HomeComponent'
  },
  {
    vNode: mockVNode2,
    vm: mockVM2,
    name: 'UserProfile'
  }
]

// 生成翻译文件
batchGenerateTranslations(
  components,
  path.resolve(__dirname, 'src/locales'),
  ['zh', 'en', 'ja']
).then(result => {
  console.log(`处理了 ${result.componentCount} 个组件`)
  console.log(`生成了 ${result.textCount} 个翻译条目`)
  console.log(`输出路径: ${result.outputPath}`)
})

📊 性能优化建议

1. 批量处理大型应用

// 对于包含大量组件的应用,建议分批处理
async function processLargeApp(components) {
  const batchSize = 50
  for (let i = 0; i < components.length; i += batchSize) {
    const batch = components.slice(i, i + batchSize)
    await batchGenerateTranslations(batch, './locales', ['zh', 'en'])
  }
}

2. 条件性处理组件

// 只处理需要国际化的组件
const componentsToTranslate = allComponents.filter(component => {
  return component.options.i18n !== false // 组件选项中设置 i18n: false 可跳过处理
})

batchGenerateTranslations(componentsToTranslate, './locales', ['zh', 'en'])

🐛 调试和开发

启用调试模式

const debugOptions = {
  debugMode: true,
  showOriginalText: true
}

translateComponent(this._vnode, this, null, languageData, debugOptions)

查看映射关系

import { getPropertyMapping } from 'vue-auto-i18n-plus'

// 获取自动生成的映射关系
const mapping = getPropertyMapping()
console.log(mapping)

// 可以将映射关系保存为文件供参考
const fs = require('fs')
fs.writeFileSync('./mapping.json', JSON.stringify(mapping, null, 2))

🎯 最佳实践

性能优化

  • 使用 batchSize 配置控制批处理大小
  • 启用 throttleDelay 防止频繁触发
  • 对于大型应用考虑使用懒加载策略
  • 定期清理不需要的翻译键

维护建议

  • 定期运行 batchGenerateTranslations 更新翻译文件
  • 使用 mapping.json 文件理解自动生成的键名
  • 在开发环境中启用调试模式便于排查问题
  • 建立翻译键命名规范,避免冲突

兼容性处理

  • 插件支持现代浏览器(Chrome 36+, Firefox 34+, Safari 9+)
  • 对于老旧浏览器会自动降级处理
  • 移动端浏览器基本兼容
  • Node.js 环境下可用于构建时生成翻译文件

⚠️ 注意事项

  1. 自动生成的 property 键名基于文本内容生成,确保唯一性
  2. 插件会在组件挂载后自动处理文本内容的多语言替换
  3. 支持中文、英文等多语言文本的自动识别
  4. 无需修改现有模板代码即可实现多语言支持
  5. 在生产环境中建议关闭调试模式以提升性能
  6. 对于动态生成的内容,可能需要手动触发重新翻译
  7. 复杂的组件结构可能需要调整 batchSizethrottleDelay 参数

📞 故障排除

常见问题及解决方案

  1. 翻译内容未生效

    • 检查翻译文件是否正确加载
    • 确认组件是否在 mounted 生命周期中调用翻译函数
    • 查看控制台是否有错误信息
  2. 自动生成的键名不符合预期

    • 调整 propertyPrefix 配置
    • 检查文本内容是否符合翻译条件
    • 使用 minTextLengthmaxTextLength 调整识别范围
  3. 性能问题

    • 降低 batchSize
    • 增加 throttleDelay 延迟
    • 使用 excludeTagsexcludeClasses 排除不需要处理的元素
  4. 浏览器兼容性问题

    • 检查控制台的兼容性检测结果
    • 确保运行环境支持 ES6+ 特性
    • 对于老旧浏览器考虑使用 polyfill