Skip to content

Repository files navigation

Reshape Plugin Util

npmtestsdependenciescoverage

A little set of utilities for reshape plugins

Note: This project is in early development, and versioning is a little different. Read this for more details.

Installation

npm i reshape-plugin-util --save

Note: This project is compatible with node v6+ only

Usage

This is just a small utility that contains a couple a useful functions when developing reshape plugins.

modifyNodes(tree, match, transform)

Given a reshape AST, a function that will return any node that matches given criteria, and a function that receives matched nodes and returns one or more modified nodes, returns a modified AST.

Example: Using modifyNodes to modify a node's content

constutil=require('reshape-plugin-util')module.exports=functionyellPlugin(tree){returnutil.modifyNodes(tree,(node)=>node.name==='p',(node)=>{node.content=node.content.map((n)=>Object.assign(n,{content: n.content.toUpperCase()}))returnnode})}

Input:

<p>hello world!</p>

Output:

<p>HELLO WORLD!</p>

Example: Using modifyNodes to remove a node

constutil=require('reshape-plugin-util')module.exports=functionremoveNodePlugin(tree){returnutil.modifyNodes(tree,(node)=>node.name==='remove',(node)=>{returnnull})}

Input:

<p>before</p><remove>hello world!</remove><p>after</p>

Output:

<p>before</p><p>after</p>

Example: Using modifyNodes to add extra nodes

constutil=require('reshape-plugin-util')module.exports=functionechoPlugin(tree){returnutil.modifyNodes(tree,(node)=>node.name==='echo',(node)=>{if(!node.attrs)node.attrs={}if(!node.attrs.class)node.attrs.class=[]node.attrs.class.push('echo')node.name='div'return[node,node]})}

Input:

<p>before</p><echo>echo</echo><p>after</p>

Output:

<p>before</p><divclass='echo'>echo</div><divclass='echo'>echo</div><p>after</p>

You can also return a promise from either function and it will work fine.

validateNode(node)

Given a single reshape AST node, checks it for formatting errors. Example:

constutil=require('reshape-plugin-util')util.validateNode({type: 'text',content: ['foo','bar'],location: {line: 1,col: 1}})// => Error: text node content must be a string// From: plugin-util// Node: {// type: 'text',// content: ['foo', 'bar'],// location: { line: 1, col: 1 }// }

validateTree(tree)

Recursively validates each node in a given reshape AST tree.

constutil=require('reshape-plugin-util')util.validateNode({type: 'tag',name: 'div'content: [{content: 'foo',location: {line: 1,col: 4}}],location: {line: 1,col: 1}})// => Error: node missing "type" attribute// From: plugin-util// Node: {// content: 'foo',// location: { line: 1, col: 4}// }

License & Contributing

About

a little helper for building reshape plugins

Resources

Contributing

Stars

4 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages