From 54a8eb9fd43f05a9187cc87979ac2fcf98a54793 Mon Sep 17 00:00:00 2001 From: Conduitry Date: Sat, 4 May 2019 10:38:30 -0400 Subject: [PATCH] expose svelte.walk (#2661) --- site/content/docs/04-compile-time.md | 32 ++++++++++++++++++++++++++++ src/index.ts | 1 + 2 files changed, 33 insertions(+) diff --git a/site/content/docs/04-compile-time.md b/site/content/docs/04-compile-time.md index 7dd1e371f6..4d4f05f2b4 100644 --- a/site/content/docs/04-compile-time.md +++ b/site/content/docs/04-compile-time.md @@ -280,6 +280,38 @@ const { code } = svelte.preprocess(source, [ ``` +### `svelte.walk` + +```js +walk(ast: Node, { + enter(node: Node, parent: Node)?: void, + leave(node: Node, parent: Node)?: void +}) +``` + +--- + +The `walk` function provides a way to walk to abstract syntax trees generated by the parser, using the compiler's own built-in instance of [estree-walker](https://github.com/Rich-Harris/estree-walker). + +The walker takes an abstract syntax tree to walk and an object with two optional methods: `enter` and `leave`. For each node, `enter` is called (if present). Then, unless `this.skip()` is called during `enter`, each of the children are traversed, and then `leave` is called on the node. + + +```js +const svelte = require('svelte/compiler'); +svelte.walk(ast, { + enter(node, parent) { + do_something(node); + if (should_skip_children(node)) { + this.skip(); + } + }, + leave(node, parent) { + do_something_else(node); + } +}); +``` + + ### `svelte.VERSION` --- diff --git a/src/index.ts b/src/index.ts index c80b449825..81163ef962 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,5 @@ export { default as compile } from './compile/index'; export { default as preprocess } from './preprocess/index'; +export { walk } from 'estree-walker'; export const VERSION = '__VERSION__'; \ No newline at end of file