8

CKEditor系列(四)支持动态多语言i18n

 2 years ago
source link: https://www.daozhao.com/10220.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

CKEditor系列(四)支持动态多语言i18n

如果您发现本文排版有问题,可以先点击下面的链接切换至老版进行查看!!!

CKEditor系列(四)支持动态多语言i18n

多语言文件结构

先看下CKEditor4的多语言文件长什么样子

//src/lang/zh-cn.js
CKEDITOR.lang[ 'zh-cn' ] = {
        editor: '所见即所得编辑器',
        common: {
                editorHelp: '按 ALT+0 获得帮助',
                keyboard: {
                        8: '退格键',
                },
        }
};

也就是直接将对应的语言值提前写入到文件中去。

使用多语言变量

有时候公司会有自己的多语言平台,公司项目实现多语言语言将它改成这样才行

//src/lang/zh-cn.js
CKEDITOR.lang[ 'zh-cn' ] = {
        editor: window.i18n['ck4.editor'],
        common: {
                editorHelp: window.i18n['ck4.common.editorHelp'],
                keyboard: {
                        8: window.i18n['ck4.common.keyboard'],
                },
        }
};

然后我们再根据项目中的语言来控制对应的window.i18n里面的值。

为了让CKEditor的更方便独立管理,我们有时需要将它独立成一个项目。这时候CKEditor这个项目在打包的时候,其实很可能是没有window.i18n的,及时有也不行(以/src/lang/zh-cn.js里面的editor为例),我们需要的是让它的value为window.i18n['ck4.editor'],而不是它当前的值所见即所得编辑器,因为我们需的是个动态的变量,而不是当前某个静态的字符串。

将字符串替换成"变量"

因为我们直接简单JavaScript的话不容直接将一个变量作为value给一个对象,所以想到了可以借助于babel这样的工具,在它的眼里,一个js文件里面的值都只是字符串,所谓的变量也只是稍微有点“特殊”而已。

我们可以将自己多语言文件//src/lang/zh-cn.js简单改造后,再解析成AST(抽象语法树),然后再进行后续操作。

CKEDITOR.lang[ 'zh-cn' ] = {
        editor: "window.i18n['ck4.editor']",
        common: {
                editorHelp: "window.i18n['ck4.common.editorHelp']",
                keyboard: {
                        8: "window.i18n['ck4.common.keyboard']",
                },
        }
};

对的,就是将这个变量的作为string来作为value,bable的工作就是把"window.i18n['ck4.editor']"替换成window.i18n['ck4.editor']

babel插件

我们可以将上述的转换过程写成一个babel插件

module.exports = function({types, template}, options, dirname){
    return {
        visitor: {
            StringLiteral: function (path, state) {
                // 未转换前value形如为"window.i18n['ck4.editor']"的字符串
                if (path.node.value.match(/^window/)) {
                    path.replaceWithSourceString(path.node.value);
                    // path.replaceWith(template.ast(path.node.value)); // 亦可
                }
            }
        }
    }
};

上的注释写的很清楚了,使用path.replaceWithSourceString(path.node.value)或者 path.replaceWith(template.ast(path.node.value))两种方式都可以完成需求

我们根据公司的多语言平台的使用要求改造CKEditor编辑的多语言文件内容,主要的难点在于怎么把里面key的value只是使用变量,而非该变量的值,变量的求值过程是在我们项目使用的时候进行,这样就实现了多语言的动态化。借助babel和AST来帮助我们处理这个转换过程。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK