1.4.0 • Published 2 years ago

tvt v1.4.0

Weekly downloads
5
License
Apache License 2....
Repository
-
Last release
2 years ago

使用

安装

npm install -g tvt

or

yarn global add tvt

配置

使用tvt前,需要在命令运行目录的package.json下指定以下配置项:

配置项类型必填项默认值含义
importPathstring-指定在 VUE SFC 中自动中引入的vue-i18n对象的相对路径,详细见下文路径配置
patternstring"**/*.vue"node-glob匹配文件模式字符串
ignorestringstring[]["node_modules/**"]node-glob配置项ignore
outputstring"i18n/zh-CN.json"指定导出的中文 JSON 文件的路径
// 默认配置
const default = {
  pattern: "**/*.vue",
  ignore: ["node_modules/**"],
  output: "i18n/zh-CN.json"
};

tvt内部会处理在 VUE 组件的script内部的中文字符,为了兼容位于export default {} 外部中文字符的情况,采用直接引入vue-i18n对象的方式,所以必须指定从vue-i18n导出的对象的全局相对路径,建议使用@别名的路径解析方式,利用webpackresolve.alias配置也十分的简单:

const path = require('path');

module.exports = {
  //...
  resolve: {
    alias: {
      "@": path.resolve(__dirname, './src'),
    },
  },
};

或者在vue-cli中:

const path = require("path");
module.exports = {
  configureWebpack: {
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "./src"),
      },
    },
  },
}

vue-i18n 的拓展

鉴于目前vue国际化解决方案主要是vue-i18n,所以 tvt内部结合vue-i18n注入到组件中的对象来对 VUE 组件中的中文字符进行转换,不过使用前需要对vue-i18n导出的对象进行一些小小的改造。

一般来说,vue-i18n的使用在<template>内部主要通过$t这样注入的方法,同时每个 VUE 组件中也都会包含一个$i18n对象,那么为了能够对在模板字符串内部的中文字符进行转换。那么我们对$i18n拓展出一个tExtend方法,用于处理在模板字符串内部中文字符的转换情况。

import Vue from "vue";
import VueI18n from "vue-i18n";
import cn from "./cn.json";

Vue.use(VueI18n);
// 通过选项创建 VueI18n 实例
const i18n = new VueI18n({
  locale: "cn", // 设置地区
  fallbackLocale: "cn",
  messages: {
    cn,
  },
});

/**
 * 转换模板字符串内部%s字符的方法
 */
i18n.tExtend = (key, values) => {
  let result = i18n.t(key);

  if (Array.isArray(values) && values.length) {
    values.forEach((v) => {
      result = result.replace(/%s/, v);
    });
  }
  return result;
};

export default i18n;

示例

例如如下 SFC 内部的插值语法中包含一个 JS 模板字符串如下:

<template>
  <div>
    {{ `你的钱包余额:${money}` }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      money: 10,
    };
  },
};
</script>

tvt提取的中文为:

{
  "9ef86bfdc5f84d52634c2732a454e3f8": "你的钱包余额:%s"
}

自动转换的结果为:

<div>
  {{ $i18n.tExtend('9ef86bfdc5f84d52634c2732a454e3f8', [money]) }}
</div>

实现

详细可见个人博客的文章解析 —— 国际化解决方案 - icodex

tvt

1.2.0

2 years ago

1.3.7

2 years ago

1.3.6

2 years ago

1.3.5

2 years ago

1.3.4

2 years ago

1.3.3

2 years ago

1.3.2

2 years ago

1.4.0

2 years ago

1.3.1

2 years ago

1.3.0

2 years ago

1.3.9

2 years ago

1.3.8

2 years ago

1.0.0

2 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago