add typescript supports
This commit is contained in:
parent
cdc732ada7
commit
de90684f40
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@voerkai18n/cli": "workspace:^1.0.6",
|
"@voerkai18n/cli": "workspace:^1.0.6",
|
||||||
"@voerkai18n/runtime": "^1.0.0"
|
"@voerkai18n/runtime": "workspace:^1.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -12,7 +12,7 @@
|
|||||||
//"suppressImplicitAnyIndexErrors":true,
|
//"suppressImplicitAnyIndexErrors":true,
|
||||||
/* Language and Environment */
|
/* Language and Environment */
|
||||||
"target": "ES2015", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
"target": "ES2015", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||||
"lib": ["ES2015"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
//"lib": ["ES2015"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||||
"experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
"experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
||||||
"emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
"emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||||
@ -100,7 +100,7 @@
|
|||||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||||
|
"allowJs": true,
|
||||||
/* Completeness */
|
/* Completeness */
|
||||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||||
|
@ -66,7 +66,7 @@ function generateFormatterFile(langName,{isTypeScript,formattersFolder,templateC
|
|||||||
|
|
||||||
module.exports =async function compile(langFolder,opts={}){
|
module.exports =async function compile(langFolder,opts={}){
|
||||||
const options = normalizeCompileOptions(opts);
|
const options = normalizeCompileOptions(opts);
|
||||||
let { moduleType,inlineRuntime,isTypeScript } = options;
|
let { moduleType,isTypeScript } = options;
|
||||||
// 如果自动则会从当前项目读取,如果没有指定则会是esm
|
// 如果自动则会从当前项目读取,如果没有指定则会是esm
|
||||||
if(moduleType==="auto"){
|
if(moduleType==="auto"){
|
||||||
moduleType = findModuleType(langFolder)
|
moduleType = findModuleType(langFolder)
|
||||||
@ -139,26 +139,17 @@ module.exports =async function compile(langFolder,opts={}){
|
|||||||
}
|
}
|
||||||
logger.log(t(" - idMap文件: {}"),path.basename(idMapFile))
|
logger.log(t(" - idMap文件: {}"),path.basename(idMapFile))
|
||||||
// 嵌入运行时源码
|
// 嵌入运行时源码
|
||||||
if(inlineRuntime && !isTypeScript ){
|
|
||||||
const runtimeSourceFolder = path.join(require.resolve("@voerkai18n/runtime"),"../..")
|
if(!isInstallDependent("@voerkai18n/runtime")){
|
||||||
fs.copyFileSync(
|
installVoerkai18nRuntime(langFolder)
|
||||||
path.join(runtimeSourceFolder,"dist",`runtime.${moduleType === 'esm' ? 'mjs' : 'cjs'}`),
|
logger.log(t(" - 安装运行时: {}"),"@voerkai18n/runtime")
|
||||||
path.join(langFolder,"runtime.js")
|
}else{
|
||||||
)
|
updateVoerkai18nRuntime(langFolder)
|
||||||
logger.log(t(" - 运行时: {}"),"runtime.js")
|
logger.log(t(" - 更新运行时:{}"),"@voerkai18n/runtime")
|
||||||
}else{//如果不嵌入则需要安装运行时依赖
|
}
|
||||||
if(!isInstallDependent("@voerkai18n/runtime")){
|
|
||||||
installVoerkai18nRuntime(langFolder)
|
|
||||||
logger.log(t(" - 安装运行时: {}"),"@voerkai18n/runtime")
|
|
||||||
}else{
|
|
||||||
updateVoerkai18nRuntime(langFolder)
|
|
||||||
logger.log(t(" - 更新运行时:{}"),"@voerkai18n/runtime")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const templateContext = {
|
const templateContext = {
|
||||||
scopeId:projectPackageJson.name,
|
scopeId:projectPackageJson.name,
|
||||||
inlineRuntime,
|
|
||||||
languages,
|
languages,
|
||||||
defaultLanguage,
|
defaultLanguage,
|
||||||
activeLanguage,
|
activeLanguage,
|
||||||
|
@ -91,7 +91,7 @@ program
|
|||||||
.command('compile')
|
.command('compile')
|
||||||
.description(t('编译指定项目的语言包'))
|
.description(t('编译指定项目的语言包'))
|
||||||
.option('-D, --debug', t('输出调试信息'))
|
.option('-D, --debug', t('输出调试信息'))
|
||||||
.option('--no-inline-runtime', t('不嵌入运行时源码'))
|
.option('-t, --typescript')
|
||||||
.option('-m, --moduleType [types]', t('输出模块类型,取值auto,esm,cjs'), 'esm')
|
.option('-m, --moduleType [types]', t('输出模块类型,取值auto,esm,cjs'), 'esm')
|
||||||
.argument('[location]', t('工程项目所在目录'),"./")
|
.argument('[location]', t('工程项目所在目录'),"./")
|
||||||
.hook("preAction",async function(location){
|
.hook("preAction",async function(location){
|
||||||
@ -100,7 +100,7 @@ program
|
|||||||
})
|
})
|
||||||
.action(async (location,options) => {
|
.action(async (location,options) => {
|
||||||
location = getProjectSourceFolder(location)
|
location = getProjectSourceFolder(location)
|
||||||
options.isTypeScript = isTypeScriptProject()
|
options.isTypeScript = options.typescript==undefined ? isTypeScriptProject() : options.typescript
|
||||||
const langFolder = path.join(location,"languages")
|
const langFolder = path.join(location,"languages")
|
||||||
if(!fs.existsSync(langFolder)){
|
if(!fs.existsSync(langFolder)){
|
||||||
logger.error(t("语言包文件夹<{}>不存在",langFolder))
|
logger.error(t("语言包文件夹<{}>不存在",langFolder))
|
||||||
|
@ -1,25 +1,17 @@
|
|||||||
{{if moduleType === "esm"}}
|
{{if moduleType === "esm"}}
|
||||||
import messageIds from "./idMap.js" // 语言ID映射文件
|
import messageIds from "./idMap.js" // 语言ID映射文件
|
||||||
{{if inlineRuntime }}import runtime from "./runtime.js" // 运行时
|
import { translate,VoerkaI18nScope } from "@voerkai18n/runtime"
|
||||||
const { translate,i18nScope } = runtime
|
|
||||||
import defaultFormatters from "./formatters/{{defaultLanguage}}.js" // 默认语言格式化器
|
|
||||||
{{if defaultLanguage === activeLanguage}}const activeFormatters = defaultFormatters{{else}}import activeFormatters from "./formatters/{{activeLanguage}}.js"{{/if}} // 激活语言格式化器
|
|
||||||
{{else}}import { translate,i18nScope } from "@voerkai18n/runtime"
|
|
||||||
{{if defaultLanguage === activeLanguage}}const activeFormatters = defaultFormatters{{else}}import activeFormatters from "@voerkai18n/runtime/formatters/{{activeLanguage}}.js"{{/if}}
|
{{if defaultLanguage === activeLanguage}}const activeFormatters = defaultFormatters{{else}}import activeFormatters from "@voerkai18n/runtime/formatters/{{activeLanguage}}.js"{{/if}}
|
||||||
{{/if}}
|
|
||||||
import defaultMessages from "./{{defaultLanguage}}.js"
|
import defaultMessages from "./{{defaultLanguage}}.js"
|
||||||
{{if defaultLanguage === activeLanguage}}const activeMessages = defaultMessages{{else}}import activeMessages from "./{{activeLanguage}}.js"{{/if}}
|
{{if defaultLanguage === activeLanguage}}const activeMessages = defaultMessages{{else}}import activeMessages from "./{{activeLanguage}}.js"{{/if}}
|
||||||
{{else}}
|
{{else}}
|
||||||
const messageIds = require("./idMap")
|
const messageIds = require("./idMap")
|
||||||
{{if inlineRuntime }}const { translate,i18nScope } = require("./runtime.js")
|
const { translate,i18nScope } = require("@voerkai18n/runtime")
|
||||||
const defaultFormatters = require("./formatters/{{defaultLanguage}}.js")
|
|
||||||
{{if defaultLanguage === activeLanguage}}const activeFormatters = defaultFormatters{{else}}const activeFormatters = require("./formatters/{{activeLanguage}}.js"){{/if}}
|
|
||||||
{{else}}const { translate,i18nScope } = require("@voerkai18n/runtime")
|
|
||||||
const defaultFormatters = require("@voerkai18n/runtime/formatters/{{defaultLanguage}}.js")
|
const defaultFormatters = require("@voerkai18n/runtime/formatters/{{defaultLanguage}}.js")
|
||||||
{{if defaultLanguage === activeLanguage}}const activeFormatters = defaultFormatters{{else}}const activeFormatters = require("@voerkai18n/runtime/formatters/{{activeLanguage}}.js"){{/if}}
|
{{if defaultLanguage === activeLanguage}}const activeFormatters = defaultFormatters{{else}}const activeFormatters = require("@voerkai18n/runtime/formatters/{{activeLanguage}}.js"){{/if}}
|
||||||
{{/if}}
|
|
||||||
const defaultMessages = require("./{{defaultLanguage}}.js") // 默认语言包
|
const defaultMessages = require("./{{defaultLanguage}}.js") // 默认语言包
|
||||||
{{if defaultLanguage === activeLanguage}}const activeMessages = defaultMessages{{else}}const activeMessages = require("./{{activeLanguage}}.js"){{/if}} {{/if}}
|
{{if defaultLanguage === activeLanguage}}const activeMessages = defaultMessages{{else}}const activeMessages = require("./{{activeLanguage}}.js"){{/if}}
|
||||||
|
{{/if}}
|
||||||
|
|
||||||
// 语言配置文件
|
// 语言配置文件
|
||||||
const scopeSettings = {{@ settings}}
|
const scopeSettings = {{@ settings}}
|
||||||
@ -34,7 +26,7 @@ const loaders = { {{each languages}}{{if $value.name !== defaultLanguage}}
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 语言作用域
|
// 语言作用域
|
||||||
const scope = new i18nScope({
|
const scope = new VoerkaI18nScope({
|
||||||
...scopeSettings, // languages,defaultLanguage,activeLanguage,namespaces,formatters
|
...scopeSettings, // languages,defaultLanguage,activeLanguage,namespaces,formatters
|
||||||
id : "{{scopeId}}", // 当前作用域的id,自动取当前工程的package.json的name
|
id : "{{scopeId}}", // 当前作用域的id,自动取当前工程的package.json的name
|
||||||
debug : false, // 是否在控制台输出高度信息
|
debug : false, // 是否在控制台输出高度信息
|
||||||
|
@ -1,12 +1,7 @@
|
|||||||
import messageIds from "./idMap" // 语言ID映射文件
|
import messageIds from "./idMap" // 语言ID映射文件
|
||||||
{{if inlineRuntime && !isTypeScript }}import runtime from "./runtime" // 运行时
|
import { translate,VoerkaI18nScope } from "@voerkai18n/runtime"
|
||||||
const { translate,i18nScope } = runtime
|
|
||||||
import defaultFormatters from "./formatters/{{defaultLanguage}}" // 默认语言格式化器
|
|
||||||
{{if defaultLanguage === activeLanguage}}const activeFormatters = defaultFormatters{{else}}import activeFormatters from "./formatters/{{activeLanguage}}"{{/if}} // 激活语言格式化器
|
|
||||||
{{else}}import { translate,i18nScope } from "@voerkai18n/runtime"
|
|
||||||
import defaultFormatters from "./formatters/{{defaultLanguage}}" // 默认语言格式化器
|
import defaultFormatters from "./formatters/{{defaultLanguage}}" // 默认语言格式化器
|
||||||
{{if defaultLanguage === activeLanguage}}const activeFormatters = defaultFormatters{{else}}import activeFormatters from "@voerkai18n/runtime/formatters/{{activeLanguage}}"{{/if}}
|
{{if defaultLanguage === activeLanguage}}const activeFormatters = defaultFormatters{{else}}import activeFormatters from "@voerkai18n/runtime/formatters/{{activeLanguage}}"{{/if}}
|
||||||
{{/if}}
|
|
||||||
import defaultMessages from "./{{defaultLanguage}}"
|
import defaultMessages from "./{{defaultLanguage}}"
|
||||||
{{if defaultLanguage === activeLanguage}}const activeMessages = defaultMessages{{else}}import activeMessages from "./{{activeLanguage}}"{{/if}}
|
{{if defaultLanguage === activeLanguage}}const activeMessages = defaultMessages{{else}}import activeMessages from "./{{activeLanguage}}"{{/if}}
|
||||||
|
|
||||||
@ -23,7 +18,7 @@ const loaders = { {{each languages}}{{if $value.name !== defaultLanguage}}
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 语言作用域
|
// 语言作用域
|
||||||
const scope = new i18nScope({
|
const scope = new VoerkaI18nScope({
|
||||||
...scopeSettings, // languages,defaultLanguage,activeLanguage,namespaces,formatters
|
...scopeSettings, // languages,defaultLanguage,activeLanguage,namespaces,formatters
|
||||||
id : "{{scopeId}}", // 当前作用域的id,自动取当前工程的package.json的name
|
id : "{{scopeId}}", // 当前作用域的id,自动取当前工程的package.json的name
|
||||||
debug : false, // 是否在控制台输出高度信息
|
debug : false, // 是否在控制台输出高度信息
|
||||||
|
256
packages/runtime/index.d.ts
vendored
256
packages/runtime/index.d.ts
vendored
@ -1,130 +1,156 @@
|
|||||||
|
declare global {
|
||||||
|
export type VoerkaI18nILanguageMessages = Record<string, string>
|
||||||
|
export interface VoerkaI18nLanguagePack {
|
||||||
|
[key: string]: VoerkaI18nILanguageMessages
|
||||||
|
}
|
||||||
|
export interface VoerkaI18nManagerSettings {
|
||||||
|
debug?: boolean
|
||||||
|
defaultLanguage: string
|
||||||
|
activeLanguage: string
|
||||||
|
formatters: VoerkI18nFormatters
|
||||||
|
languages: VoerkaI18nLanguage[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export class VoerkaI18nManager {
|
||||||
|
constructor(settings: VoerkaI18nManagerSettings)
|
||||||
|
get settings(): Required<VoerkaI18nManagerSettings> // 配置参数
|
||||||
|
get scopes(): VoerkaI18nScope[] // 注册的报有i18nScope实例q
|
||||||
|
get activeLanguage(): string // 当前激活语言名称
|
||||||
|
get defaultLanguage(): string // 默认语言名称
|
||||||
|
get languages(): VoerkaI18nSupportedLanguages // 支持的语言列表
|
||||||
|
get formatters(): VoerkI18nFormatters // 内置格式化器{*:{$config,$types,...},zh:{$config,$types,...},en:{$config,$types,...}}
|
||||||
|
get defaultMessageLoader(): VoerkI18nLoader // 默认语言包加载器
|
||||||
|
// 通过默认加载器加载文件
|
||||||
|
loadMessagesFromDefaultLoader(newLanguage: string, scope: VoerkaI18nScope): Promise<VoerkaI18nILanguageMessages>
|
||||||
|
change(language: string): Promise<void>
|
||||||
|
register(scope: VoerkaI18nScope): Promise<void>
|
||||||
|
registerFormatter(name: string, formatter: VoerkI18nFormatter, options?: { language: string | string[] }): void
|
||||||
|
registerDefaultLoader(fn: VoerkI18nLoader): void
|
||||||
|
refresh(): Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
export type VoerkaLanguageMessages = Record<string,string>
|
export type Voerkai18nIdMap = Record<string, number>
|
||||||
export interface VoerkaLanguagePack {
|
|
||||||
[key: string]: VoerkaLanguageMessages
|
export interface VoerkaI18nLanguage {
|
||||||
}
|
name: string
|
||||||
export interface VoerkaI18nManagerSettings {
|
title?: string
|
||||||
debug?:boolean
|
default?: boolean
|
||||||
defaultLanguage: string
|
fallback?: string
|
||||||
activeLanguage : string
|
}
|
||||||
formatters : VoerkI18nFormatters
|
|
||||||
languages :VoerkaI18nLanguage[]
|
export interface VoerkaI18nSupportedLanguages {
|
||||||
|
[key: string]: VoerkaI18nLanguage
|
||||||
|
}
|
||||||
|
|
||||||
|
export type VoerkI18nFormatter = (value: string, ...args: any[]) => string
|
||||||
|
export type VoerkI18nFormatterConfigs = Record<string, any>
|
||||||
|
|
||||||
|
export type VoerkI18nFormatters = Record<string, ({
|
||||||
|
$types?: Record<string, VoerkI18nFormatter>
|
||||||
|
$config?: Record<string, string>
|
||||||
|
} & {
|
||||||
|
[key: string]: VoerkI18nFormatter
|
||||||
|
}) | (() => Promise<any>)>
|
||||||
|
|
||||||
|
export type VoerkI18nLoader = () => Awaited<Promise<any>>
|
||||||
|
export interface VoerkI18nLoaders {
|
||||||
|
[key: string]: VoerkI18nLoader
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VoerkaVoerkaI18nScopeOptions {
|
||||||
|
id?: string
|
||||||
|
debug?: boolean
|
||||||
|
languages: VoerkaI18nLanguage[]
|
||||||
|
defaultLanguage: string // 默认语言名称
|
||||||
|
activeLanguage: string // 当前语言名称
|
||||||
|
default: VoerkaI18nILanguageMessages // 默认语言包
|
||||||
|
messages: VoerkaI18nILanguageMessages // 当前语言包
|
||||||
|
idMap: Voerkai18nIdMap // 消息id映射列表
|
||||||
|
formatters: VoerkI18nFormatters // 当前作用域的格式化函数列表{<lang>: {$types,$config,[格式化器名称]: () => {},[格式化器名称]: () => {}}}
|
||||||
|
loaders: VoerkI18nLoaders; // 异步加载语言文件的函数列表
|
||||||
|
}
|
||||||
|
|
||||||
|
export var VoerkaI18n: VoerkaI18nManager
|
||||||
}
|
}
|
||||||
|
|
||||||
export class I18nManager{
|
|
||||||
constructor(settings:VoerkaI18nManagerSettings)
|
|
||||||
get settings():Required<VoerkaI18nManagerSettings> // 配置参数
|
|
||||||
get scopes():i18nScope[] // 注册的报有i18nScope实例q
|
|
||||||
get activeLanguage():string // 当前激活语言名称
|
|
||||||
get defaultLanguage():string // 默认语言名称
|
|
||||||
get languages():VoerkaI18nSupportedLanguages // 支持的语言列表
|
|
||||||
get formatters():VoerkI18nFormatters // 内置格式化器{*:{$config,$types,...},zh:{$config,$types,...},en:{$config,$types,...}}
|
|
||||||
get defaultMessageLoader():VoerkI18nLoader // 默认语言包加载器
|
|
||||||
// 通过默认加载器加载文件
|
|
||||||
loadMessagesFromDefaultLoader(newLanguage:string,scope:i18nScope):Promise<VoerkaLanguageMessages>
|
|
||||||
change(language:string):Promise<void>
|
|
||||||
register(scope:i18nScope):Promise<void>
|
|
||||||
registerFormatter(name:string,formatter:VoerkI18nFormatter,options?:{language:string | string[]}):void
|
|
||||||
registerDefaultLoader(fn:VoerkI18nLoader):void
|
|
||||||
refresh():Promise<void>
|
|
||||||
|
|
||||||
}
|
export class VoerkaI18nScope {
|
||||||
|
constructor(options: VoerkaVoerkaI18nScopeOptions, callback?: Function)
|
||||||
|
get id(): string // 作用域唯一id
|
||||||
|
get debug(): boolean // 调试开关
|
||||||
|
get defaultLanguage(): string // 默认语言名称
|
||||||
|
get activeLanguage(): string // 默认语言名称
|
||||||
|
get default(): VoerkaI18nILanguageMessages // 默认语言包
|
||||||
|
get messages(): VoerkaI18nILanguageMessages // 当前语言包
|
||||||
|
get idMap(): Voerkai18nIdMap // 消息id映射列表
|
||||||
|
get languages(): VoerkaI18nSupportedLanguages // 当前作用域支持的语言列表[{name,title,fallback}]
|
||||||
|
get loaders(): VoerkI18nLoaders // 异步加载语言文件的函数列表
|
||||||
|
get global(): VoerkaI18nManager // 引用全局VoerkaI18n配置,注册后自动引用
|
||||||
|
get formatters(): VoerkI18nFormatters // 当前作用域的所有格式化器定义 {<语言名称>: {$types,$config,[格式化器名称]: () = >{},[格式化器名称]: () => {}}}
|
||||||
|
get activeFormatters(): VoerkI18nFormatters // 当前作用域激活的格式化器定义 {$types,$config,[格式化器名称]: () = >{},[格式化器名称]: () = >{}}
|
||||||
|
get activeFormatterConfig(): VoerkI18nFormatterConfigs // 当前格式化器合并后的配置参数,参数已经合并了全局格式化器中的参数
|
||||||
|
|
||||||
export type Voerkai18nIdMap = Record<string,number>
|
/**
|
||||||
|
* 在全局注册作用域当前作用域
|
||||||
export interface VoerkaI18nLanguage{
|
* @param {*} callback 注册成功后的回调
|
||||||
name:string
|
*/
|
||||||
title?:string
|
register(callback: Function): void
|
||||||
default?:boolean
|
/**
|
||||||
fallback?:string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface VoerkaI18nSupportedLanguages {
|
|
||||||
[key :string]:VoerkaI18nLanguage
|
|
||||||
}
|
|
||||||
|
|
||||||
export type VoerkI18nFormatter = (value:string,...args:any[]) => string
|
|
||||||
export type VoerkI18nFormatterConfigs = Record<string,any>
|
|
||||||
|
|
||||||
export type VoerkI18nFormatters = Record<string,({
|
|
||||||
$types?:Record<string,VoerkI18nFormatter>
|
|
||||||
$config?:Record<string,string>
|
|
||||||
} & {
|
|
||||||
[key:string]:VoerkI18nFormatter
|
|
||||||
}) | (() => Awaited<Promise<any>>)>
|
|
||||||
|
|
||||||
export type VoerkI18nLoader = ()=>Awaited<Promise<any>>
|
|
||||||
export interface VoerkI18nLoaders {
|
|
||||||
[key :string]:VoerkI18nLoader
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface I18nScopeOptions{
|
|
||||||
id?:string
|
|
||||||
debug?:boolean
|
|
||||||
languages:VoerkaI18nLanguage[]
|
|
||||||
defaultLanguage:string // 默认语言名称
|
|
||||||
activeLanguage:string // 当前语言名称
|
|
||||||
default:VoerkaLanguageMessages // 默认语言包
|
|
||||||
messages:VoerkaLanguageMessages // 当前语言包
|
|
||||||
idMap:Voerkai18nIdMap // 消息id映射列表
|
|
||||||
formatters:VoerkI18nFormatters // 当前作用域的格式化函数列表{<lang>: {$types,$config,[格式化器名称]: () => {},[格式化器名称]: () => {}}}
|
|
||||||
loaders:VoerkI18nLoaders; // 异步加载语言文件的函数列表
|
|
||||||
}
|
|
||||||
|
|
||||||
export class i18nScope {
|
|
||||||
constructor(options:I18nScopeOptions, callback?:Function)
|
|
||||||
get id():string // 作用域唯一id
|
|
||||||
get debug():boolean // 调试开关
|
|
||||||
get defaultLanguage():string // 默认语言名称
|
|
||||||
get activeLanguage():string // 默认语言名称
|
|
||||||
get default():VoerkaLanguageMessages // 默认语言包
|
|
||||||
get messages(): VoerkaLanguageMessages // 当前语言包
|
|
||||||
get idMap():Voerkai18nIdMap // 消息id映射列表
|
|
||||||
get languages():VoerkaI18nSupportedLanguages // 当前作用域支持的语言列表[{name,title,fallback}]
|
|
||||||
get loaders() :VoerkI18nLoaders // 异步加载语言文件的函数列表
|
|
||||||
get global():I18nManager // 引用全局VoerkaI18n配置,注册后自动引用
|
|
||||||
get formatters():VoerkI18nFormatters // 当前作用域的所有格式化器定义 {<语言名称>: {$types,$config,[格式化器名称]: () = >{},[格式化器名称]: () => {}}}
|
|
||||||
get activeFormatters():VoerkI18nFormatters // 当前作用域激活的格式化器定义 {$types,$config,[格式化器名称]: () = >{},[格式化器名称]: () = >{}}
|
|
||||||
get activeFormatterConfig():VoerkI18nFormatterConfigs // 当前格式化器合并后的配置参数,参数已经合并了全局格式化器中的参数
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 在全局注册作用域当前作用域
|
|
||||||
* @param {*} callback 注册成功后的回调
|
|
||||||
*/
|
|
||||||
register(callback:Function):void
|
|
||||||
/**
|
|
||||||
* 注册格式化器
|
* 注册格式化器
|
||||||
*/
|
*/
|
||||||
registerFormatter(name:string, formatter:VoerkI18nFormatter, { language , global }:{language:string | string[] , global:boolean}):void
|
registerFormatter(name: string, formatter: VoerkI18nFormatter, { language, global }: { language: string | string[], global: boolean }): void
|
||||||
/**
|
/**
|
||||||
* 注册多种格式化器
|
* 注册多种格式化器
|
||||||
*/
|
*/
|
||||||
registerFormatters(formatters:VoerkI18nFormatters,asGlobal?:boolean):void
|
registerFormatters(formatters: VoerkI18nFormatters, asGlobal?: boolean): void
|
||||||
/**
|
/**
|
||||||
* 注册默认文本信息加载器
|
* 注册默认文本信息加载器
|
||||||
*/
|
*/
|
||||||
registerDefaultLoader(fn:Function):void
|
registerDefaultLoader(fn: Function): void
|
||||||
/**
|
/**
|
||||||
* 获取指定语言信息
|
* 获取指定语言信息
|
||||||
* @param {*} language
|
* @param {*} language
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
getLanguage(language:string):VoerkaLanguageMessages
|
getLanguage(language: string): VoerkaI18nILanguageMessages
|
||||||
hasLanguage(language:string):boolean
|
hasLanguage(language: string): boolean
|
||||||
refresh(newLanguage:string):Promise<void>
|
refresh(newLanguage: string): Promise<void>
|
||||||
on():void
|
on(): void
|
||||||
off():void
|
off(): void
|
||||||
offAll():void
|
offAll(): void
|
||||||
change(language:string):Promise<void>
|
change(language: string): Promise<void>
|
||||||
|
}
|
||||||
|
export type VoerkI18nFormatterConfigs = Record<string, any>
|
||||||
|
// 翻译函数
|
||||||
|
export var translate: {
|
||||||
|
(message: string, ...args: (string | Function)[]): string
|
||||||
|
(message: string, vars?: Record<string, any>): string
|
||||||
|
}
|
||||||
|
export interface CreateFormatterOptions {
|
||||||
|
normalize?: (value: any) => any // 对输入值进行规范化处理,如进行时间格式化时,为了提高更好的兼容性,支持数字时间戳/字符串/Date等,需要对输入值进行处理,如强制类型转换等
|
||||||
|
params?: string[] | null // 可选的,声明参数顺序,如果是变参的,则需要传入null
|
||||||
|
configKey?: string // 声明该格式化器在$config中的路径,支持简单的使用.的路径语法
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type Primitive = string | number | boolean | null | undefined
|
||||||
|
|
||||||
export declare type translate =((message:string,...args:(string | Function)[])=>string)
|
export interface FormatterDefine {
|
||||||
| ((message:string,vars:Record<string,any>)=>string)
|
(this: VoerkI18nFormatterConfigs, value: any, ...args: Primitive[]): string
|
||||||
|
(this: VoerkI18nFormatterConfigs, value: any, arg1: Primitive, $config: VoerkI18nFormatterConfigs): string
|
||||||
|
(this: VoerkI18nFormatterConfigs, value: any, arg1: Primitive, arg2: Primitive, $config: VoerkI18nFormatterConfigs): string
|
||||||
|
(this: VoerkI18nFormatterConfigs, value: any, arg1: Primitive, arg2: Primitive, arg3: Primitive, $config: VoerkI18nFormatterConfigs): string
|
||||||
|
configurable?: boolean
|
||||||
|
}
|
||||||
|
// 创建格式化器
|
||||||
|
export type CreateFormatterType = (fn: Function, options: CreateFormatterOptions, defaultParams: Record<string, any>) => FormatterDefine
|
||||||
|
export var createFormatter: CreateFormatterType
|
||||||
|
export var Formatter: CreateFormatterType
|
||||||
|
|
||||||
|
export type CreateFlexFormatterType = (fn: Function, options: CreateFormatterOptions, defaultParams: Record<string, any>) => FormatterDefine
|
||||||
|
export var createFlexFormatter: CreateFlexFormatterType
|
||||||
|
export var FlexFormatter: CreateFlexFormatterType
|
||||||
|
export var getDataTypeName:(value:any) => string
|
||||||
|
export var toDate: (value: any) => Date | number
|
||||||
|
export var toNumber: (value: any,defaultValue:number) => number
|
||||||
|
export var toBoolean: (value: any) => boolean
|
||||||
|
|
||||||
declare global {
|
|
||||||
var VoerkaI18n:I18nManager
|
|
||||||
var t:((message:string,...args:(string | Function)[])=>string)
|
|
||||||
| ((message:string,vars:Record<string,any>)=>string)
|
|
||||||
}
|
|
@ -1,12 +1,10 @@
|
|||||||
const {DataTypes,getDataTypeName,isPlainObject,isFunction,isNumber,isNothing,deepMerge,deepMixin} = require("./utils")
|
const {DataTypes,getDataTypeName,isFunction,deepMerge,toBoolean} = require("./utils")
|
||||||
const {getInterpolatedVars,replaceInterpolatedVars} = require("./interpolate")
|
|
||||||
const {createFormatter,Formatter,FlexFormatter,createFlexFormatter} = require("./formatter")
|
const {createFormatter,Formatter,FlexFormatter,createFlexFormatter} = require("./formatter")
|
||||||
const { toDate } = require("./datatypes/datetime")
|
const { toDate } = require("./datatypes/datetime")
|
||||||
const { toNumber } = require("./datatypes/numeric")
|
const { toNumber } = require("./datatypes/numeric")
|
||||||
|
|
||||||
const EventEmitter = require("./eventemitter")
|
const EventEmitter = require("./eventemitter")
|
||||||
const inlineFormatters = require("./formatters")
|
const inlineFormatters = require("./formatters")
|
||||||
const i18nScope = require("./scope")
|
const VoerkaI18nScope = require("./scope")
|
||||||
const { translate } = require("./translate")
|
const { translate } = require("./translate")
|
||||||
|
|
||||||
// 默认语言配置
|
// 默认语言配置
|
||||||
@ -36,19 +34,19 @@ const defaultLanguageSettings = {
|
|||||||
* VoerkaI18n.off("change",(language)=>{})
|
* VoerkaI18n.off("change",(language)=>{})
|
||||||
*
|
*
|
||||||
* */
|
* */
|
||||||
class I18nManager extends EventEmitter{
|
class VoerkaI18nManager extends EventEmitter{
|
||||||
constructor(settings={}){
|
constructor(settings={}){
|
||||||
super()
|
super()
|
||||||
if(I18nManager.instance!=null){
|
if(VoerkaI18nManager.instance!=null){
|
||||||
return I18nManager.instance;
|
return VoerkaI18nManager.instance;
|
||||||
}
|
}
|
||||||
I18nManager.instance = this;
|
VoerkaI18nManager.instance = this;
|
||||||
this._settings = deepMerge(defaultLanguageSettings,settings)
|
this._settings = deepMerge(defaultLanguageSettings,settings)
|
||||||
this._scopes=[] // 保存i18nScope实例
|
this._scopes=[] // 保存VoerkaI18nScope实例
|
||||||
this._defaultMessageLoader = null // 默认语言包加载器
|
this._defaultMessageLoader = null // 默认语言包加载器
|
||||||
}
|
}
|
||||||
get settings(){ return this._settings } // 配置参数
|
get settings(){ return this._settings } // 配置参数
|
||||||
get scopes(){ return this._scopes } // 注册的报有i18nScope实例q
|
get scopes(){ return this._scopes } // 注册的报有VoerkaI18nScope实例q
|
||||||
get activeLanguage(){ return this._settings.activeLanguage} // 当前激活语言 名称
|
get activeLanguage(){ return this._settings.activeLanguage} // 当前激活语言 名称
|
||||||
get defaultLanguage(){ return this._settings.defaultLanguage} // 默认语言名称
|
get defaultLanguage(){ return this._settings.defaultLanguage} // 默认语言名称
|
||||||
get languages(){ return this._settings.languages} // 支持的语言列表
|
get languages(){ return this._settings.languages} // 支持的语言列表
|
||||||
@ -100,8 +98,8 @@ const defaultLanguageSettings = {
|
|||||||
* @param {*} scope
|
* @param {*} scope
|
||||||
*/
|
*/
|
||||||
async register(scope){
|
async register(scope){
|
||||||
if(!(scope instanceof i18nScope)){
|
if(!(scope instanceof VoerkaI18nScope)){
|
||||||
throw new TypeError("Scope must be an instance of I18nScope")
|
throw new TypeError("Scope must be an instance of VoerkaI18nScope")
|
||||||
}
|
}
|
||||||
this._scopes.push(scope)
|
this._scopes.push(scope)
|
||||||
await scope.refresh(this.activeLanguage)
|
await scope.refresh(this.activeLanguage)
|
||||||
@ -158,20 +156,14 @@ const defaultLanguageSettings = {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports ={
|
module.exports ={
|
||||||
isNumber,
|
|
||||||
isNothing,
|
|
||||||
isPlainObject,
|
|
||||||
isFunction,
|
|
||||||
toDate,
|
toDate,
|
||||||
toNumber,
|
toNumber,
|
||||||
deepMerge,
|
toBoolean,
|
||||||
deepMixin,
|
deepMerge,
|
||||||
getInterpolatedVars,
|
VoerkaI18nManager,
|
||||||
replaceInterpolatedVars,
|
|
||||||
I18nManager,
|
|
||||||
translate,
|
translate,
|
||||||
i18nScope,
|
VoerkaI18nScope,
|
||||||
createFormatter,
|
createFormatter,
|
||||||
Formatter,
|
Formatter,
|
||||||
createFlexFormatter,
|
createFlexFormatter,
|
||||||
|
@ -4,12 +4,12 @@
|
|||||||
"description": "核心运行时",
|
"description": "核心运行时",
|
||||||
"main": "./dist/index.cjs",
|
"main": "./dist/index.cjs",
|
||||||
"module": "./dist/index.esm.js",
|
"module": "./dist/index.esm.js",
|
||||||
"types":"./index.d.ts",
|
"typings":"./index.d.ts",
|
||||||
"homepage": "https://gitee.com/zhangfisher/voerka-i18n",
|
"homepage": "https://gitee.com/zhangfisher/voerka-i18n",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://gitee.com/zhangfisher/voerka-i18n.git"
|
"url": "git+https://gitee.com/zhangfisher/voerka-i18n.git"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "echo \"Error: no test specified\" && exit 1",
|
"test": "echo \"Error: no test specified\" && exit 1",
|
||||||
"build": "rollup -c",
|
"build": "rollup -c",
|
||||||
|
@ -32,25 +32,25 @@ export default [
|
|||||||
terser()
|
terser()
|
||||||
],
|
],
|
||||||
external:["@babel/runtime"]
|
external:["@babel/runtime"]
|
||||||
},
|
|
||||||
{
|
|
||||||
input: './index.js',
|
|
||||||
output: [
|
|
||||||
{
|
|
||||||
file: 'dist/runtime.cjs',
|
|
||||||
exports:"auto",
|
|
||||||
format:"cjs",
|
|
||||||
sourcemap:true
|
|
||||||
},
|
|
||||||
{
|
|
||||||
file: 'dist/runtime.mjs',
|
|
||||||
exports:"default",
|
|
||||||
format:"esm",
|
|
||||||
sourcemap:true
|
|
||||||
}
|
|
||||||
],
|
|
||||||
plugins:[
|
|
||||||
commonjs()
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
// {
|
||||||
|
// input: './index.js',
|
||||||
|
// output: [
|
||||||
|
// {
|
||||||
|
// file: 'dist/runtime.cjs',
|
||||||
|
// exports:"auto",
|
||||||
|
// format:"cjs",
|
||||||
|
// sourcemap:true
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// file: 'dist/runtime.mjs',
|
||||||
|
// exports:"default",
|
||||||
|
// format:"esm",
|
||||||
|
// sourcemap:true
|
||||||
|
// }
|
||||||
|
// ],
|
||||||
|
// plugins:[
|
||||||
|
// commonjs()
|
||||||
|
// ]
|
||||||
|
// }
|
||||||
]
|
]
|
@ -1,6 +1,6 @@
|
|||||||
const { DataTypes,isPlainObject, isFunction, getByPath, deepMixin,deepClone } = require("./utils");
|
const { DataTypes,isPlainObject, isFunction, getByPath, deepMixin,deepClone } = require("./utils");
|
||||||
|
|
||||||
module.exports = class i18nScope {
|
module.exports = class VoerkaI18nScope {
|
||||||
constructor(options = {}, callback) {
|
constructor(options = {}, callback) {
|
||||||
this._id = options.id || Date.now().toString() + parseInt(Math.random() * 1000);
|
this._id = options.id || Date.now().toString() + parseInt(Math.random() * 1000);
|
||||||
this._debug = options.debug == undefined ? process && process.env && process.env.NODE_ENV === "development" : options.debug; // 当出错时是否在控制台台输出错误信息
|
this._debug = options.debug == undefined ? process && process.env && process.env.NODE_ENV === "development" : options.debug; // 当出错时是否在控制台台输出错误信息
|
||||||
@ -24,8 +24,8 @@ module.exports = class i18nScope {
|
|||||||
this._initiLanguages()
|
this._initiLanguages()
|
||||||
// 如果不存在全局VoerkaI18n实例,说明当前Scope是唯一或第一个加载的作用域,则自动创建全局VoerkaI18n实例
|
// 如果不存在全局VoerkaI18n实例,说明当前Scope是唯一或第一个加载的作用域,则自动创建全局VoerkaI18n实例
|
||||||
if (!globalThis.VoerkaI18n) {
|
if (!globalThis.VoerkaI18n) {
|
||||||
const { I18nManager } = require("./");
|
const { VoerkaI18nManager } = require("./");
|
||||||
globalThis.VoerkaI18n = new I18nManager({
|
globalThis.VoerkaI18n = new VoerkaI18nManager({
|
||||||
debug : this._debug,
|
debug : this._debug,
|
||||||
defaultLanguage: this._defaultLanguage,
|
defaultLanguage: this._defaultLanguage,
|
||||||
activeLanguage : this._activeLanguage,
|
activeLanguage : this._activeLanguage,
|
||||||
|
@ -414,9 +414,9 @@ function deepMerge(toObj,formObj,options={}){
|
|||||||
*/
|
*/
|
||||||
function updateVoerkai18nRuntime(srcPath){
|
function updateVoerkai18nRuntime(srcPath){
|
||||||
const projectFolder = getProjectRootFolder(srcPath || process.cwd())
|
const projectFolder = getProjectRootFolder(srcPath || process.cwd())
|
||||||
if(fs.existsSync("pnpm-lock.yaml")){
|
if(fs.existsSync(path.join(projectFolder,"pnpm-lock.yaml"))){
|
||||||
shelljs.exec("pnpm upgrade --latest @voerkai18n/runtime")
|
shelljs.exec("pnpm upgrade --latest @voerkai18n/runtime")
|
||||||
}else if(fs.existsSync("yarn.lock")){
|
}else if(fs.existsSync(path.join(projectFolder,"yarn.lock"))){
|
||||||
shelljs.exec("yarn upgrade @voerkai18n/runtime")
|
shelljs.exec("yarn upgrade @voerkai18n/runtime")
|
||||||
}else{
|
}else{
|
||||||
shelljs.exec("npm update --save @voerkai18n/runtime")
|
shelljs.exec("npm update --save @voerkai18n/runtime")
|
||||||
|
Loading…
x
Reference in New Issue
Block a user