java pack unicode,中文字符转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() ]

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值