Skip to content

Instantly share code, notes, and snippets.

@apaleslimghost
Last active January 16, 2020 08:55
Show Gist options
  • Save apaleslimghost/3fdd26b1700f6fbb9504d44977f1ffaa to your computer and use it in GitHub Desktop.
Save apaleslimghost/3fdd26b1700f6fbb9504d44977f1ffaa to your computer and use it in GitHub Desktop.

jsx-cheerio

a JSX renderer that outputs Cheerio elements

usage

/** @jsx h */
import h from '@quarterto/jsx-cheerio';

const $ = cheerio.load('<div>');
$('div').append(<h1>hello world</h1>);
var flatMap = require('@quarterto/flatmap');
function textToCheerio(text) {
return {
type: 'text',
data: text
}
}
function tagToCheerio(tagName, attrs) {
var children = [].slice.call(arguments, 2);
var parent = {
type: 'tag',
name: tagName,
attribs: attrs
};
parent.children = flatMap(children, toCheerio).map(function(child, i, children) {
child.next = children[i + 1] || null;
child.prev = children[i - 1] || null;
child.parent = parent;
return child;
});
return parent;
}
function toCheerio(it) {
if(it.type) return [it];
if(Array.isArray(it)) return flatMap(it, toCheerio);
if(typeof it === 'string') return [textToCheerio(it)];
if(!it) return [];
throw new TypeError('Invalid JSX child, expected element, string, array, or falsy, got ' + it);
}
module.exports = tagToCheerio;
module.exports.cheerioRoot = function(node) {
return {
type: 'root',
name: 'root',
attribs: {},
children: toCheerio(node),
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment