textrun-javascript
v0.2.0
Published
This package provides [Text-Runner](https://github.com/kevgo/text-runner) actions for JavaScript code snippets inside documentation.
Downloads
10
Readme
Text-Runner JavaScript Actions
This package provides Text-Runner actions for JavaScript code snippets inside documentation.
Installation
To use these actions, add this package as a development dependency by running npm i -D textrun-javascript or yarn i -D textrun-javascript.
Run JavaScript
Assume your documentation instructs the reader to run a line of JavaScript. It could contain something like this:
Let's run our first JavaScript command:
```js
console.log("Hello world!")
```
When you assign the javascript/runnable type to this document part, Text-Runner executes the JavaScript similar to how the user would:
Let's run our first JavaScript command:
<a type="javascript/runnable">
```js
console.log("Hello world")
```
</a>
You can simplify this to:
Let's run our first JavaScript command:
<pre type="javascript/runnable">
console.log("Hello world!")
</pre>
Asynchronous JavaScript
The javascript/runnable action waits for the code
block to finish. To wait for asynchronous code, add the placeholder <CALLBACK>
where your code would call the callback when its done. Only one placeholder is
allowed per code block. Example:
function asyncFoo(done) {
console.log("some async work")
done()
}
asyncFoo(<CALLBACK>)
You can also use // ...
as the placeholder:
function asyncFoo(done) {
console.log("some async work")
done()
}
asyncFoo(function (err) {
// ...
})
Sharing JavaScript variables
Let's say your documentation contains two regions of JavaScript that share a variable:
const text = "hello"
and
const complete = text + "world"
Each JavaScript region runs in its own isolated environment. The second region
would not see the variable text
from the first region. They do share the
global
object, though. To share local variables between different regions of
Javascript, this step replaces all occurrences of const⎵
, var⎵
, let⎵
, and
this.
with global.
As an example, const foo = 123
gets turned into
global.foo = 123
, thereby making foo accessible in all code regions.
Validate JavaScript
The javascript/non-runnable action marks documented JavaScript code that should not be executed. Example:
<pre type="javascript/non-runnable">
const a = 1;
</pre>