RegExp.escape = function (s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
let hh=['','-','=','+',"{",'[','(','*',"~","/","%",">","<","!","^","|","?"];
var fs = require('fs');
var file = './code.js';
var yuanshi = fs.readFileSync(file, 'utf8');
var newstr = '';
yuanshi.split('\n').forEach(function (item) {
newstr += replaceRequire(item) + "\n";
});
console.log(newstr);
function replaceRequire(str) {
let s, arr = [],yinhao = '"';
str = str.replace(/'.*?'|".*?"/g, function (match, offset, string) {
let ran = (Math.random() + "").slice(2);
arr.push({ran: ran, str: match});
return ran;
});
let str1 = str.slice(str.lastIndexOf('//'));
str = str.slice(0, str.lastIndexOf('//'));
arr.forEach(item => {
str = str.replace(item.ran, item.str);
str1 = str1.replace(item.ran, item.str);
});
function handler(match, p1,p2) {
let flag=false;
for(let i in hh){
flag = flag||match.trim().indexOf(hh[i]+'require')==0;
}
if(!flag){
return match;
}
p1=p1||p2;
let re = new RegExp(`${yinhao}.*?${RegExp.escape(match)}.*?${yinhao}`);
let search = str.search(re);
return search == -1 ? match.replace(p1, (pp = p1.split(''), pp.splice(1, 0, '@'), pp.join(''))) : match;
}
s = str.replace(/.?require\s*\(\s*('.*?')\s*\)/g, handler);
yinhao = "'";
s = s.replace(/.?require\s*\(\s*(".*?")\s*\)/g, handler);
return s.slice(0) + str1;
}
/*
// 测试用例如下:
var fs = require('@fs');
// require('fs');
var a = require('@lib/a'), b = require('@lib/b'); // c = require('c');
var h = "test require('lib/a')";
var h2 = 'test require("lib/a")';
require ('@c');
require ( '@d' );
$require('e');
$.require('f');
requireAll('g');
*/
内部使用的解析require
最新推荐文章于 2022-03-12 15:56:52 发布