Skip to content

Commit 255ba0b

Browse files
authored
fix(docs): Add example to README.md
1 parent 9a48ade commit 255ba0b

File tree

1 file changed

+57
-1
lines changed

1 file changed

+57
-1
lines changed

README.md

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ npm run build
5050
npm pack
5151
```
5252

53-
## Use the JavaScript API
53+
## Use the JavaScript API with Node.JS
5454

5555
```js
5656
//
@@ -111,3 +111,59 @@ async function main() {
111111

112112
main().catch(console.error);
113113
```
114+
115+
## Use the JavaScript API in a web browser
116+
117+
```html
118+
<!DOCTYPE html>
119+
<html lang="en">
120+
<head>
121+
<title>C++ Playground</title>
122+
</head>
123+
<body>
124+
<script type="module">
125+
import {
126+
Parser,
127+
AST,
128+
ASTKind,
129+
} from "https://unpkg.com/cxx-frontend@latest/dist/index.js";
130+
131+
const response = await fetch(Parser.DEFAULT_WASM_BINARY_URL);
132+
133+
const wasmBinary = new Uint8Array(await response.arrayBuffer());
134+
135+
await Parser.init({ wasmBinary });
136+
137+
const source = `int main()\n{\n return 0;\n}\n`;
138+
139+
const parser = new Parser({
140+
path: "source.cc",
141+
source,
142+
});
143+
144+
parser.parse();
145+
146+
const rows = [];
147+
148+
const ast = parser.getAST();
149+
150+
ast?.walk().preVisit((node, depth) => {
151+
if (node instanceof AST)
152+
rows.push(" ".repeat(depth) + ASTKind[node.getKind()]);
153+
});
154+
155+
parser.dispose();
156+
157+
const sourceOutput = document.createElement("pre");
158+
sourceOutput.style.borderStyle = "solid";
159+
sourceOutput.innerText = source;
160+
document.body.appendChild(sourceOutput);
161+
162+
const astOutput = document.createElement("pre");
163+
astOutput.style.borderStyle = "solid";
164+
astOutput.innerText = rows.join("\n");
165+
document.body.appendChild(astOutput);
166+
</script>
167+
</body>
168+
</html>
169+
```

0 commit comments

Comments
 (0)