国际惯例,先来一个小demo
输入数据
function square(n) {
return n * n;
}处理数据
astFn() {
const code = `function square(n) {
return n * n;
}`;
//得到 AST 语法树
const ast = babylon.parse(code); traverse(ast, {
enter(path) {
console.log("enter: " + path.node.type);
//如下的语句匹配到 return 中的 n 与参数 n,并且将它替换为 x。
if (path.node.type === "Identifier" && path.node.name === "n") {
path.node.name = "x";
}
}
});
generate(ast, {}, code);//将 AST 转换为代码
console.log(generate(ast, {}, code).code );//打印出转换后的 JavaScript 代码
}
输出数据
function square(x) {
return x * x;
}我们看一下我们得到的 AST 树
接下来我们插入一段 把 VUE 组件转换为微信小程序组件正则版本的处理
二、 简单粗暴的版本(VUE 组件转换为微信小程序组件)
没有使用 AST 将 VUE 组件转换成小程序组件的简易版本介绍
下方是两段代码,简单的逻辑,实现思路,匹配目标字符串,替换字符,然后生成文件。
regs:{//通过标签匹配来替换对应的小程序支持的标签
toViewStartTags: /(<h1)|(<s)|(<em)|(<ul)|(<li)|(<dl)|(<i)|(<span)/g,
toViewEndTags: /(</h1>)|(</s>)|(</em>)|(</ul>)|(</li>)|(</dl>)|(</i>)|(</span>)/g,
toBlockStartTags: /(<div)|(<p)/g,
toBlockEndTags: /(</div>)|(</p>)/g,
},
signObj: {//通过标签查找来分离脚本,模板和CSS
tempStart: '<template>',
tempEnd: '</template>',
styleStart: '<style scoped>',
styleEnd: '</style>',
scriptStart: '<script>',
scriptEnd: '</script>'
}上方是正则版本的一些模板匹配规则,经过后续的一系列处理把一个 VUE组件处理得到对应的小程序的 WXML ,WXSS,JSON,JS,4个文件。
//文件
const wxssFilePath = path.join(dirPath, `${mpFile}.wxss`);
const jsFilePath = path.join(dirPath, `${mpFile}.js`);
const wxmlFilePath = path.join(dirPath, `${mpFile}.wxml`);
const jsonFilePath = path.join(dirPath, `${mpFile}.json`);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath);
}
fs.writeFile(wxssFilePath, wxssContent, err => {
if (err) throw err;
//console.log(`dist目录下生成${mpFile}.wxss文件成功`);
fs.writeFile(jsFilePath, jsContent, err => {










