Front-end engineering development of "international theme and switch" scheme small mind

1 Introduction

Over the years, the front end with the advent of Vue and React so some of the framework, the development of methods have undergone rapid changes. The author practitioners 10 years, the use of components of Microsoft Asp.Net too early to render the server components, JSP JAVA template control system, used Jquery framework based on a number of (EasyUI, JqueryUI) components, ExtJS, Dojo, and so on. Although these front end components (or called a frame) after another, but the basic idea is the same, the browser is to optimize the operation or Dom operation. It is true to say, seemed to epitomize the characteristics of the new framework is too general, especially in the case of front-end engineering development of large-scale promotion, and now the new framework before in the jquery-based front-end development model has not a level up. Information system consisting of a software development team personnel, in particular, can see this point, more and more front-end engineers, but also on the front-end is growing. A technology or a complex system later, often 分而治之a problem to solve faced, isolated "before and after the end of the" development model, which is raised slowly in recent years and are used in many development teams. But there is SPA (single page) system, seems to understand the front-end development has caused a great deal of distress.

He said so much change, so now complex information systems, front-end of the business in the form of composition modules in the end there is no change in it. Or, in the face now popular micro-services framework, front-end application scenario is what happened.

Just recently a large front-end production systems face big transformation, the system probably includes a platform (page container), several business modules. Service modules need to be registered in the form of a menu to the platform, and a platform nested within the opening (tab form, as a whole).

Integrated .png

We looked at a lot of open source development framework, often a front-end engineering, which contains the base module, but also includes business modules, and a system on a SPA, the so-called large single-page application. However, the real R & D team, tend to have a lot of independent micro-Services development team, each team has its own technology system. If the organization in accordance with the development of a single page in the form of large, integrated package seem to cross a lot of cross-team, and block the update process seems to be very complicated. So naturally the most appropriate way for each business module is developed in the form of a SPA application, the responsibility of the various teams (platform also true), eventually unified the various modules integrated into the platform in certain forms. So a lot of open-source development framework for complex information systems tend to be less research and development mode. Under the current structure, we can not do a complex system is a SPA this format.

So a better way, but it is still handled before a similar complex system, due to the integrated module embedded in each business, in fact, was a platform iframe front of a container vessel, the only difference is that after the division of business modules, each module can SPA in the form of independent, I think this is the original intention of micro-services reform it.

This module determines the form of the service module and the container module integration, affecting the system has become 统一性the key is located. In this regard, there are two content, an important consideration in front-end development framework design. This is also the language of today, the focus of a unified international process; unifying theme of another block switch.

Having said all this nonsense, straight to the point. In this paper, React + Antd + Umijs this set of front-end solution, based on a presentation to share front-end engineering development process and switching solutions topic internationalization process. FIG example of the first switching effect:

theme-change.gif

2, source code and use

React currently based front-end and Antd more and more projects, and the use of open source scaffolding Umijs seems to have become mandatory for small and medium projects. First program under the code tags and descriptions to share today:

gitee:https://gitee.com/BeautifulHao/theme-demo-app

//本地演示
git clone https://gitee.com/BeautifulHao/theme-demo-app.git
cd theme-demo-app
yarn install
yarn start

3, international programs

​国际化是一个全局性的设置,所以作为单页应用,最理想的设置地方最好是最外层的包装组件,而结合umijs,最合适的就是layout组件,或者说是route的最外层嵌套组件设置全局国际化。react的国际化有两个库,一个是react-intl,另一个是react-intl-universal,本文介绍的是react-intl-universal。

ant design 组件国际化

结合官方的文档:https://ant.design/docs/react/i18n-cn,列举项目源码说明src/layouts/index.js


import React, { PureComponent } from 'react'
//antd国际化包装组件
import { ConfigProvider } from 'antd';
import intl from 'react-intl-universal';
//antd国际化资源
import zhCN from 'antd/es/locale-provider/zh_CN';
import enUS from 'antd/es/locale-provider/en_US';
//本地国际化资源
import enTranslationsData from '../locale/en-US';
import zhTranslationsData from '../locale/zh-CN';
//国际化键常量和基于cookie全局设置方法
import { Locale_en_US, Locale_zh_CN, getCookieLocale } from '../utils/i18n';

//包含常规一些国际化字符串
require('intl/locale-data/jsonp/en.js');
require('intl/locale-data/jsonp/zh.js');

const AntdTranslations = {
  [Locale_zh_CN]: zhCN,
  [Locale_en_US]: enUS,
}

class BasicLayout extends PureComponent {

  state = {initDone: false}

  componentWillMount () {
    //通过平台容器集设置的cookie获取当前全局环境的国际化设置
    const currentLocale = getCookieLocale();
    //初始化react-intl-universal 组件国际化设置
    intl.init({
      currentLocale,
      locales: {
        [Locale_zh_CN]: { ...zhTranslationsData },
        [Locale_en_US]: { ...enTranslationsData },
      }
    }).then(() => {
      this.setState({initDone: true});
    });
  }

  render () {
    const currentLocale = getCookieLocale();
    return (
      //按照antd官网设置国际化包装器ConfigProvider
      this.state.initDone &&
          <ConfigProvider locale={AntdTranslations[currentLocale]}>{this.props.children}</ConfigProvider>
    )
  }
}

本地国际化资源格式(../locale/en-US):

const enUS ={
  "test.helloworld": "hello world",
  "test.show":"hello,I'm from english context!",
  "test.buttom":"test buttom",
  "test.themeAndLocale":'Please Select The Theme & Locale:',
  "test.pageShow":'page show:'
}

export default enUS

业务组件国际化使用

//引入组件
import intl from 'react-intl-universal';
//调用方法获取
intl.get('test.themeAndLocale')

4、主题切换方案

可行方案介绍

  • css换肤:生成多套主题css,在页面加载时根据主题选择加载指定css

  • less换肤:采用动态Less机制,通过js动态编译less变量修改css(可参考:less换肤

css主题切换介绍

从效果来说,动态Less换肤优于css换肤(页面不刷新),但对于单个业务模块而言,虽然作为SPA应用,但是模块内多个功能地址都将作为菜单独立打开,每次加载一个页面都将动态编译一次less,性能将有很大的消耗。所以在行文开头说明的复杂系统的场景下less换肤不是一个最优的选择。那么css换肤呢,综合考量了下,的确还是能够达到预期的效果的,尤其是antd一个主色就能搞定一个主题的场景(antd),而且主题切换往往就是antd皮肤切换。所以要实现主题切换,就得从antd下手。

生成多份主题文件

Antd style CSS files can be introduced through the link tags, and the project also requested to provide several sets of Antd theme style. First thought can directly Quguan network can directly customize and download the CSS file. However, the answer is no. But as the industry's best open-source projects, Antd provides a method to customize custom theme styles, detailed instructions in the official website there is a custom theme, however Antd but only provides LESS style customizable features, does not provide ready-made CSS style file customize and download functions.

So naturally feasible way is:

  • Access to official standards LESS master file
  //一般就在当前项目下
  node_modules/antd/dist/antd.less
  • Subsequently LESS a custom document, introduced into the main file, covering the specified style variable according to the needs
  @import "../node_modules/antd/dist/antd.less";   
// Import Ant Design styles by less entry
  
  @primary-color: #1890ff;
  • Use lessc tools needed to compile the final CSS file
lessc -js theme-demo-app-default.less ../public/theme/theme-demo-app-default.css

Based on the above ideas, we just need to do more css file to several different @ primary-color color.
Multi-themed .png
Multi-themed 2.png

Loads the specified theme css

Start from the single-page application entry file index.html, at the beginning of the page load to load the specified css, html template file umijs combination, we can process as follows: document.ejs

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Theme-Demo Application</title>
  <script>
    window.publicPathString = "<%= context.publicPath %>"
    document.title = "<%= context.config.plugins[0][1].title %>"
  </script>
  <script src="<%= context.publicPath %>theme/append-theme.js"></script>
</head>
<body>
  <div id="root"></div>
</body>
</html>
// append-theme.js
//根据cookie动态添加sup-ui的样式文件
var themeHandle = {
  getCookie: function(name) {
    name = name + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1);
         }
         if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length);
         }
     }
    return undefined;
  },
  appendTheme: function() {
    var publicPath = window.publicPathString;
    var theme = this.getCookie('theme');
    theme = theme ? theme : 'default'
    var link = document.createElement('link');
    link.type = 'text/css';
    link.id = 'theme-' + theme;
    link.rel = 'stylesheet';
    link.href = publicPath + 'theme/theme-demo-app-' + theme + '.css';
    document.getElementsByTagName('head')[0].appendChild(link);
  },
};

themeHandle.appendTheme();

主要的过程就是从cookie中获取指定主题设置,然后加载不同的antd主题css.

reference:

https://www.jianshu.com/p/35e0581629d2
https://boycgit.github.io/customize-antd-css/

Guess you like

Origin www.cnblogs.com/blogsfuh/p/11442279.html