background

The company’s project years ago suddenly required the Marketing Department to add a new internationalization function to achieve the switching function between Chinese and English. The project was developed with vue+ elementUi, which had a large number of words, which were basically mindless and tedious requirements. We prepared to develop a simple plug-in to directly replace the whole world.

Train of thought

Install vue-i18n in vue and use node to read.vue and.js ending files, filter all text with re, then use random character replacement, write random character and character specified text generation object to a JS for later switching. Another youdao plug-in can directly convert Chinese into English and export it to another JS (considering the effect of literal translation, it is still handed over to business translator).

The idea is simple. Start writing code

Step 1: Preparation
  1. Install the vue – i18n, NPM | | yarn
  2. Create a new folder language and create files en.js and en.js in the folder language
  3. Import and mount vue-i18n in main.js, import JS file…

.

The second step reads the file

Create the node.js file and place it in the root directory

var fs = require('fs');
var path = require('path');

// Parse the folder that needs to be traversed to see the file directory structure
var filePath = path.resolve('./src');
let fileTextList = path.resolve(__dirname, './language/zh.js')

// Call the file traversal method
fileDisplay(filePath);
let textObj = {} // Generate js objects
function fileDisplay(filePath) {
  // Read the file according to the file path, return the file list
  fs.readdir(filePath, function(err, files) {
    if (err) {
      console.warn(err)
    } else {
      // Iterate over the list of files read
      files.forEach(function(filename) {
        // Get the absolute path to the current file
        var filedir = path.join(filePath, filename);
        // Obtain file information based on the file path
        fs.stat(filedir, function(eror, stats) {
          if (eror) {
            console.warn('Obtaining file stats failed');
          } else {
            var isFile = stats.isFile(); / / files
            var isDir = stats.isDirectory(); // Is a folder
            if (isFile) {
              // Perform the replacement
            }
            if (isDir) {
              fileDisplay(filedir); // Recursively, if it is a folder, continue to traverse the files under that folder}}})}); }}); }Copy the code

The third step regains the global replacement text

 replaceText(filedir){
     if (filedir.indexOf('.vue')! = = -1) {
       let fileText = fs.readFileSync(filedir, 'utf-8') // Read the file text
       // Regular replacement of Chinese characters + characters
       let data = fileText.match(/[\u4e00-\u9fa5]+[\u3002\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b]? [\u4e00-\u9fa5]+/g)
       if(data){
          data.map(item= > {
            // Generate random strings
            let randomStr = randomString(10)
               fileText = fileText.replace(new RegExp(item, 'g'), '{{$t("' + randomStr + ')}} ')
               textObj[randomStr] = item
             })
             fs.writeFile(filedir, fileText, { encoding: 'utf8' }, err= >{})}}}// Generate random character functions
 function randomString(len) {len = len | |16;var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789';varmaxPos = $chars.length;var str = ' ';for (i = 0; i < len; I++) {STR += $chars.charat (Math.floor(MathThe random () * maxPos)); }return str;
}
Copy the code
The fourth step is to generate json output

Notice that since it’s done recursively, I just stole the timer and wrote it directly

/ setTimeout(() = > {
// fs.writeFile(fileTextList, JSON.stringify(textObj), {
// encoding: 'utf8'
// }, err => {})
// }, 30000)
Copy the code
At the end

Just very simple to read the file, re replacement, but there are still a lot of problems when writing, including form binding, JS template and other re matching or almost mean, originally wanted to upload to NPM, considering the limitations of use is not passed, after a long time free to write the article, mutual love.