中文字符转unicode webpack loader实现

背景

在项目中,存在大量的中文字符定义,不论是枚举或是注释,抑或是报错信息,在工程build过后,中文信息都是存储在源码中的,第一感觉不专业,第二容易被人随便一搜就能定位到该业务逻辑源码,第三在某种条件下(根据操作系统差异),文件中的中文字符经常会乱码。遂有了念头将中文字符以unicode的形式存储到编译后的源码中。

loader实现(已废弃)

代码不多,直接上代码

import { loader } from "webpack";

export default function (this: loader.LoaderContext, content: string) {
  console.log(`正在编译文件: [${this.resourcePath}]`);
  return gbk2Unicode(content);
}

function gbk2Unicode(content: string) {
  return content.replace(/([\u0080-\uffff])/g, (str) => {
    let hex = str.charCodeAt(0).toString(16);
    for(let i = hex.length; i < 4; i ++) {
      hex = '0' + hex;
    }
    return '\\u' + hex;
  })
}

// console.log(gbk2Unicode('``测试汉字@123123,。//,/qwea啊腊八sadasqwe111'))

plugin 实现

import { Compiler } from "webpack";

export default class UnicodeWebpackPlugin {

  public apply(compiler: Compiler) {
    compiler.plugin('emit', function (compilation, callback) {
      console.log(`\n****unicode-webpack-plugin****`);
      compilation.chunks.map(chunk => {
        chunk.files.map(filename => {
          console.log('正在编译资源:', filename);
          compilation.assets[filename]._value = gbk2Unicode(compilation.assets[filename]._value);
        })
      })
      console.log(`\n****unicode-webpack-plugin end****\n`);
      callback();
    })
  }
}

function gbk2Unicode(content: string) {
  return content.replace(/([\u0080-\uffff])/g, (str) => {
    let hex = str.charCodeAt(0).toString(16);
    for (let i = hex.length; i < 4; i++) { 
      hex = '0' + hex;
    }
    return '\\u' + hex;
  })
}

在webpack中使用

在配置文件中添加以下内容

{
  plugins: [ ...someplugin, new UnicodeWebpackPlugin() ]
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容