Git Product home page Git Product logo

di18n's Introduction

di18n

自动转换、基于配置的前端国际化方案。

为什么存在

在前端国际化开发中,很多社区方案给我们带来了极大便利,但是仍有2个问题没有解决:

  • 需要手工将代码中的主语言(比如中文)替换成国际化标记;
  • 语言包应该是一种配置,不必强耦合到项目代码里。

为此,我们开发了 di18n,它能自动扫描代码中的主语言,将其替换成国际化标记;同时将语言抽取成配置,可以放到服务端保存及更新。

工作原理

di18n 会先按如下步骤扫描源码:

  • 使用 Babel 解析得到 AST,遍历 AST,并对特殊的节点进行检查,抽取出需要翻译的字符串;
  • 自动为每一个字符串分配一个 key 因随机 key 可读性差,已改成使用主语言(如中文)文案为 key;
  • 自动调用 Google 翻译服务(可选),得到一个英文的字符串。

注:对于 React,上面提到的特殊节点包括: JSXText StringLiteral TemplateLiteral 等。

扫描之后,对于源代码:

  • 构造 CallExpression 表达式 intl.t('key1')
  • 替换原有节点 path.replaceWith(newNode)
  • 将新的 AST 通过 Babel 转换为代码;
  • 使用 Prettier 格式化代码;
  • 将新的代码落盘。

对于国际化资源:

  • 将 key-value 转换为 i18n 配置文件格式。

流程图

安装

$ npm i -D di18n-cli

# or

$ yarn add  -D di18n-cli

初始化

React

$ npx di18n init

注意:TypeScript 需要将配置文件 di18n.config.js 的 prettier.parser 改为 "typescript"

Vue

$ npx di18n init --vue

转换

$ npx di18n sync

License

MIT

di18n's People

Contributors

yshaojun avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.