Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active April 8, 2018 02:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rauschma/0af308fc8004f70195d25b2cf88b5c7e to your computer and use it in GitHub Desktop.
Save rauschma/0af308fc8004f70195d25b2cf88b5c7e to your computer and use it in GitHub Desktop.

Testing JavaScript embedded in Markdown

  • Use case: Blog posts and books, not documentation for software.
  • As much code as possible should be included within the Markdown file.
  • I’m currently using § as a meta-character.
    • I’m open to alternatives. Other characters I considered: ¡ ¿ Δ ≡
    • I wanted it to be a non-ASCII character, to minimize the risk of conflicts.

Checking is opt-in

JavaScript to be checked:

<!--§check-->

```js
Math.hypot(3, 4); //→ 5
```

Code that isn’t syntactically legal:

```js
class Foo {
    constructor(name) {
        this.name = name;
    }
    ···
}
```

Defining and referring to pieces of code

<!--§id:point-->

```js
class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}
```

<!--§include:point-->

```js
const point = new Point(5, 2);
```

Including arbitrary JavaScript

Without ID: add to following code block.

<!--§js:
import {foo} from 'bar';
-->

```js
foo();
```

With ID: defines a named code block.

<!--§js:the-imports
import {foo} from 'bar';
-->

<!--§include:the-imports-->

```js
foo();
```

Checking results

Single statements

```js
console.log(3 + 4); //→ 7

function add(x, y) {
    return x + y;
}
add(3, 4); //→ 7
```

Loops

```js
const obj = {
    foo: 1,
    bar: 2,
};
for (const [k,v] of Object.entries(obj)) {
    console.log(k, v); //
}
// Output:
// 'foo' 1
// 'bar' 2
```

REPL interactions

```repl
> const x = 3;
> const y = 4;
> x + y
7
```

Configuring Babel

  • Once, at the end of a file. Is used for the whole file.
  • Always: babel-preset-env (means all latest features)
  • Explicitly: experimental plugins
<!--§babel:
{
    "plugins": ["transform-react-jsx"]
}
-->

Ideas

  • Also lint the code?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment