html语法树转html

时间:2023-02-05 22:06:06
//html语法树节点类型
const typeMap= {
    '1':function (node) {
        if(node.attrs&&node.attrs.length>0){
            node.attrs.forEach(function (item) {
                item.type='attrs'
            })
        }
        return [
            '<',
            node.tag,
            node.staticClass?[' class=',node.staticClass]:'',
            node.attrs&&node.attrs.length>0?[' ',joinSymbol(node.attrs,' ')]:'',
            '>',
            node.children,
            '</',
            node.tag,
            '>',
        ];
    },
    attrs:function (node) {
        return [node.name,'=',node.value]
    },
    '3':function (node) {
        return node.text;
    },
}
//语法树转string
function AstChildToString(children) {
    let str='';
    children.forEach(function (node) {
        str+=AstToHtml(node)
    })
    return str;
}
//元素之间添加符号
function joinSymbol(oriArr,symbol,pre) {
    if(oriArr.length===0){return '';}
    const arr=[];
    if(pre){
        arr.push(pre)
    }
    oriArr.forEach(function (node,i) {
        arr.push(node);
        if(i<oriArr.length-1){
            arr.push(symbol);
        }
    })
    if(pre){
        arr.push(pre)
    }
    return arr;
}
//语法树转string
function AstToHtml(ast){
    if(Object.prototype.toString.call(ast)==='[object Array]'){
        return AstChildToString(ast);
    }else if(Object.prototype.toString.call(ast)==='[object String]'){
        return ast;
    }else if(ast===null){
        return '';
    }
    let code=typeMap[ast.type](ast);

    if(Object.prototype.toString.call(code)==='[object Array]'){
        const arr=code.map(function(obj){
            if(Object.prototype.toString.call(obj)==='[object Object]'){
                return AstToHtml(obj);
            }else if(Object.prototype.toString.call(obj)==='[object Array]'){
                return AstToHtml(obj);
            }
            return obj;
        })
        return arr.join('');
    }else{
        return code;
    }

}
module.exports=AstToHtml;

test.js

//demo
const AstToHtml=require('../AstToHtml');
const getText=require('../utils/getText');
const compiler = require('vue-template-compiler');
async function init() {
    const html=await getText('./test.html')
    const htmlAst=compiler.compile(html).ast;
    // console.log(html)
    console.log(AstToHtml(htmlAst))
}
init()