@aligov/global-string-format

@aligov/global-string-format 提供普通文案国际化能力,业务方传入数据字典,组件返回id对应的文案。

Usage no npm install needed!

<script type="module">
  import aligovGlobalStringFormat from 'https://cdn.skypack.dev/@aligov/global-string-format';
</script>

README

@aligov/global-string-format

@aligov/global-string-format 提供普通文案国际化能力,业务方传入数据字典,组件返回id对应的文案。

主要特征

  • 提供获取普通文案的国际化能力
  • 可以在浏览器和node环境中运行
  • 基于国际化多语言标准
  • 支持 react/rax 对象作为变量
  • 同时支持 index 和 name 作为变量索引
  • 结合使用 babel-plugin-string-format 可以解决依赖组件的文案收集和透传的问题

安装

tnpm install @aligov/global-string-format --save

使用

基本使用

// src/index.js

import  stringFormat from '@aligov/global-string-format';

// 初始化一个实例,并将这个实例挂载到全局变量(window/global)上. 在一些通用组件可以直接用这个实例进行格式化.
stringFormat.init('en-US', {
  'en-US': {
    'no_variable': 'I have noe messages',
    'variable_test_for_index': 'I have {0} messages',
    'variable_test_for_name': 'I have {count} messages',
  },
  'zh-CN': {
    'no_variable': '我没有消息',
    'variable_test_for_index': '我有 {0} 条消息',
    'variable_test_for_name': '我有 {count} 条消息',
  }
});

// 输出多语言
stringFormat.format({
  id: 'no_variable',
  defaultString: 'I have noe messages'
});
// 输出
// I have noe messages

// 使用 index  作为变量的索引
stringFormat.format({
  id: 'variable_test_for_index',
  defaultString: 'I have {0} messages'

},[2])

// 输出
// I have 2 messages


// 使用 name 作为变量的缩影
stringFormat.format({
  id: 'variable_test_for_name',
  defaultString: 'I have {count} messages'
},{count: 1})

// 输出
// I have 2 messages

在其他的页面或者依赖组件中, 直接调用 stringFormat.Format , 使用首次初始化的实例进行格式化.

// src/component/other/index.js
import  stringFormat from '@aligov/global-string-format';
// 使用全局共享的实例进行多语言格式化
stringFormat.format({
  id: 'no_variable',
  defaultString: 'I have noe messages'
});
// 输出
// I have noe messages

React Dom 作为变量

import  from 'react';
import  stringFormat from '@aligov/global-string-format';
const messageCountSpan = (<span style={{color: 'red'}}>2</span>);
stringFormat.format({
  id: 'variable_test_for_index',
  defaultString: 'I have {0} messages'
},[messageCountSpan],{
  React // 注意: 需要将 React 作为参数传入
})

其他的API

使用 StringFormat 对象

1.StringFormat:使用 StringFormat 实例化。 2.format:使用StringFormat实例的format方法,返回每条id对应的文案。

import  sf from '@aligov/global-string-format';
/**
 *  @param locale Languages that need to be localized
 *  @param strings Data dictionary, ICU grammar
 */
const stringFormat = new sf.StringFormat('zh-CN', {
  'en-US': {
    'hello_world': 'hello world'
  },
  'zh-CN': {
    'hello_world': '你好,国际化'
  } 
});

// 获取传入的 strings 
stringFormat.getStrings()

// 进行格式化
stringFormat.format({
  id: 'hello_world',
  defaultString: 'hello world'
});