发出使用DOM中的React代码解析HTML

时间:2019-01-04 19:44:42

标签: javascript jquery webpack cheerio

我们在内部创建了一个Webpack加载器,以在其他项目的index.html中操纵/注入一些常见的HTML代码。

下面是一个示例React html模板-

let source = `<html>
  <body>
     <div id="root">
        <%- reactServerSideRender %>
     <div>
  </body>
</html>`;

下面是使用Cheerio的代码。

import * as $ from 'cheerio';
console.log('After cheerio', source);
let $source = $.load(source);
console.log('After cheerio', $source);

预期结果-

<html>
  <body>
     <div id="root">
        <%- reactServerSideRender %>
     <div>
  </body>
</html>

实际结果

<html>
  <body>
     <div id="root">
        <%- reactserversiderender="" %="">
        </%->
     <div>
  </body>
</html>

有关如何解决此问题的任何帮助或建议?

更新1/7/19:我能够将问题追溯到 https://github.com/cheeriojs/dom-serializer/blob/master/index.js#L82

对于我上面的代码,它被识别为TAG(我记录了elem变量的值。

element type      - tag
element attribute - { reactserversiderender: '', '%': '' }
element name      - %-

此问题是由于cheerio使用的htmlparser2模块无法正确解析html。

解决方案:使用parse5模块后,我能够解决此问题(Cheerio还计划使该项目的parse5默认解析器,但尚未发布)。下面是我必须添加才能使其正常工作的额外代码行。

const document = parse5.parse(source);
const str = parse5.serialize(document);
const $source = $.load(str);

0 个答案:

没有答案