denoland / deno

A modern runtime for JavaScript and TypeScript.
https://deno.com
MIT License
94.5k stars 5.25k forks source link

test --doc: allow import statements to be in a separate code block #25745

Open skybrian opened 1 week ago

skybrian commented 1 week ago

I'm trying out the new deno test --doc feature in the Deno 2 release candidate. It works, but might be nicer if I didn't have to write out imports in each code block.

Version: 2.0.0-rc.4

Example

Here is an import that will be needed in the following examples:

```ts
import { assertEquals } from "@std/assert";

Here's an example of how to use assertEquals:

assertEquals("hello".length, 5);

Here's a second example:

assertEquals([1, 2, 3], [1, 2, 3]);

## What it does now:

Check file:///Users/skybrian/Projects/deno/repeat-test/docs/example.md$3-6.ts Check file:///Users/skybrian/Projects/deno/repeat-test/docs/example.md$9-12.ts Check file:///Users/skybrian/Projects/deno/repeat-test/docs/example.md$15-18.ts error: TS2304 [ERROR]: Cannot find name 'assertEquals'. assertEquals([

    at file:///Users/skybrian/Projects/deno/repeat-test/docs/example.md$15-18.ts:2:5

TS2304 [ERROR]: Cannot find name 'assertEquals'.
    assertEquals("hello".length, 5);
at file:///Users/skybrian/Projects/deno/repeat-test/docs/example.md$9-12.ts:2:5

Found 2 errors.



## What I'd like it to do:

Don't report any errors, because the imports were declared in a previous code block.

## How would it work?

I don't know what's best, but here are some alternatives:

 * When there is a code block that *only* contains imports, automatically prepend it to each of the following code blocks.
 * When there is a code block that has *no* imports, reuse the imports from the previous code block.

Or, perhaps both rules?
iuioiua commented 1 week ago

Why not just add the import statement to your code blocks?

skybrian commented 1 week ago

I could, but it means there is more boilerplate in each example, which makes the article less readable. So I normally only write imports for the first example. It would be nice to be able to automatically check the examples anyway, without having to change my writing style too much to satisfy the tool.

sigmaSd commented 1 week ago

I think rust way is also interesting, it allows hiding some part of the code block if prefixed with a specific character

waldyrious commented 1 week ago

hiding some part of the code block if prefixed with a specific character

That seems interesting but the feature only works for the rendering of the markdown file in Rust's documentation pipeline. It would be nice if the .md file itself was less verbose in any markdown renderer, not just Deno's documentation generator.