package.nls.json 代表英文语言文件
{
"command.favourite.addtofavourite": "Add to Favourite",
"command.favourite.deletefavourite": "Remove from Favourite",
"command.favourite.moveup": "Move Up"
}
在 package.json 里可以用下面方式引用
"title": "%command.favourite.moveup%"
新建个 package.nls.zh-cn.json 文件是中文语言包
{
"command.favourite.addtofavourite": "添加到收藏夹",
"command.favourite.deletefavourite": "从收藏夹中删除",
"command.favourite.moveup": "上移"
}
同样方式引用,当 vscode 设置成中文时会引用中文语言包
"title": "%command.favourite.moveup%"
这是 package.json 用多语言,如果代码中也想使用多语言怎么办呢
创建 localize.ts 文件,从 code-settings-sync 插件中拷贝过来的
import { existsSync, readFileSync } from 'fs';
import { resolve } from "path";
import { extensions } from "vscode";
import { ILanguagePack } from '../model/language-pack.model';
export class Localize {
private bundle = this.resolveLanguagePack();
private options: { locale: string };
public localize(key: string, ...args: string[]): string {
const message = this.bundle[key] || key;
return this.format(message, args);
}
private init() {
try {
this.options = {
...this.options,
...JSON.parse(process.env.VSCODE_NLS_CONFIG || "{}")
};
} catch (err) {
throw err;
}
}
private format(message: string, args: string[] = []): string {
return args.length
? message.replace(
/\{(\d+)\}/g,
(match, rest: any[]) => args[rest[0]] || match
)
: message;
}
private resolveLanguagePack(): ILanguagePack {
this.init();
const languageFormat = "package.nls{0}.json";
const defaultLanguage = languageFormat.replace("{0}", "");
const rootPath = extensions.getExtension('yunan-hu.vscode-favourite')
.extensionPath;
const resolvedLanguage = this.recurseCandidates(
rootPath,
languageFormat,
this.options.locale
);
const languageFilePath = resolve(rootPath, resolvedLanguage);
try {
const defaultLanguageBundle = JSON.parse(
resolvedLanguage !== defaultLanguage
? readFileSync(resolve(rootPath, defaultLanguage), "utf-8")
: "{}"
);
const resolvedLanguageBundle = JSON.parse(
readFileSync(languageFilePath, "utf-8")
);
return { ...defaultLanguageBundle, ...resolvedLanguageBundle };
} catch (err) {
throw err;
}
}
private recurseCandidates(
rootPath: string,
format: string,
candidate: string
): string {
const filename = format.replace("{0}", `.${candidate}`);
const filepath = resolve(rootPath, filename);
if (existsSync(filepath)) {
return filename;
}
if (candidate.split("-")[0] !== candidate) {
return this.recurseCandidates(rootPath, format, candidate.split("-")[0]);
}
return format.replace("{0}", "");
}
}
export default Localize.prototype.localize.bind(new Localize());
注意 extensions.getExtension('yunan-hu.vscode-favourite') 要改为自己的发布者名,和 package.json 里的name值
language-pack.model.ts
export interface ILanguagePack {
[key: string]: string;
}
使用
import localize from '../helper/localize'
vscode.window.showErrorMessage(localize('ext.new.group.name'));
这样就可以在 ts 中使用了。