Skip to content

Commit

Permalink
docs: add @shikiji/vitepress-twoslash (#16168)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red committed Mar 15, 2024
1 parent 20bf97d commit 6f8a320
Show file tree
Hide file tree
Showing 24 changed files with 997 additions and 152 deletions.
4 changes: 4 additions & 0 deletions docs/.vitepress/config.ts
@@ -1,4 +1,5 @@
import { defineConfig, DefaultTheme } from 'vitepress'
import { transformerTwoslash } from '@shikijs/vitepress-twoslash'
import { buildEnd } from './buildEnd.config'

const ogDescription = 'Next Generation Frontend Tooling'
Expand Down Expand Up @@ -342,5 +343,8 @@ export default defineConfig({
])
return pageData
},
markdown: {
codeTransformers: [transformerTwoslash()],
},
buildEnd,
})
3 changes: 3 additions & 0 deletions docs/.vitepress/theme/index.ts
@@ -1,6 +1,8 @@
import { h } from 'vue'
import type { Theme } from 'vitepress'
import DefaultTheme from 'vitepress/theme'
import TwoslashFloatingVue from '@shikijs/vitepress-twoslash/client'
import '@shikijs/vitepress-twoslash/style.css'
import './styles/vars.css'
import HomeSponsors from './components/HomeSponsors.vue'
import AsideSponsors from './components/AsideSponsors.vue'
Expand All @@ -16,5 +18,6 @@ export default {
},
enhanceApp({ app }) {
app.component('SvgImage', SvgImage)
app.use(TwoslashFloatingVue)
},
} satisfies Theme
13 changes: 13 additions & 0 deletions docs/.vitepress/tsconfig.json
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"noImplicitOverride": true,
"noUnusedLocals": true,
"esModuleInterop": true,
"noEmit": true
},
"exclude": ["cache", "dist"]
}
13 changes: 11 additions & 2 deletions docs/config/build-options.md
Expand Up @@ -48,13 +48,22 @@ type ResolveModulePreloadDependenciesFn = (
The `resolveDependencies` function will be called for each dynamic import with a list of the chunks it depends on, and it will also be called for each chunk imported in entry HTML files. A new dependencies array can be returned with these filtered or more dependencies injected, and their paths modified. The `deps` paths are relative to the `build.outDir`. Returning a relative path to the `hostId` for `hostType === 'js'` is allowed, in which case `new URL(dep, import.meta.url)` is used to get an absolute path when injecting this module preload in the HTML head.
```js
<!-- prettier-ignore-start -->
```js twoslash
/** @type {import('vite').UserConfig} */
const config = {
build: {
// ---cut-before---
modulePreload: {
resolveDependencies: (filename, deps, { hostId, hostType }) => {
return deps.filter(condition)
}
},
},
// ---cut-after---
},
}
```
<!-- prettier-ignore-end -->

The resolved dependency paths can be further modified using [`experimental.renderBuiltUrl`](../guide/build.md#advanced-base-options).

Expand Down
8 changes: 6 additions & 2 deletions docs/config/dep-optimization-options.md
Expand Up @@ -19,7 +19,9 @@ Dependencies to exclude from pre-bundling.
:::warning CommonJS
CommonJS dependencies should not be excluded from optimization. If an ESM dependency is excluded from optimization, but has a nested CommonJS dependency, the CommonJS dependency should be added to `optimizeDeps.include`. Example:

```js
```js twoslash
import { defineConfig } from 'vite'
// ---cut---
export default defineConfig({
optimizeDeps: {
include: ['esm-dep > cjs-dep'],
Expand All @@ -37,7 +39,9 @@ By default, linked packages not inside `node_modules` are not pre-bundled. Use t

**Experimental:** If you're using a library with many deep imports, you can also specify a trailing glob pattern to pre-bundle all deep imports at once. This will avoid constantly pre-bundling whenever a new deep import is used. [Give Feedback](https://github.com/vitejs/vite/discussions/15833). For example:

```js
```js twoslash
import { defineConfig } from 'vite'
// ---cut---
export default defineConfig({
optimizeDeps: {
include: ['my-lib/components/**/*.vue'],
Expand Down
10 changes: 7 additions & 3 deletions docs/config/index.md
Expand Up @@ -50,7 +50,9 @@ Vite also directly supports TS config files. You can use `vite.config.ts` with t

If the config needs to conditionally determine options based on the command (`serve` or `build`), the [mode](/guide/env-and-mode) being used, if it's an SSR build (`isSsrBuild`), or is previewing the build (`isPreview`), it can export a function instead:

```js
```js twoslash
import { defineConfig } from 'vite'
// ---cut---
export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => {
if (command === 'serve') {
return {
Expand All @@ -73,7 +75,9 @@ It is important to note that in Vite's API the `command` value is `serve` during

If the config needs to call async functions, it can export an async function instead. And this async function can also be passed through `defineConfig` for improved intellisense support:

```js
```js twoslash
import { defineConfig } from 'vite'
// ---cut---
export default defineConfig(async ({ command, mode }) => {
const data = await asyncFunction()
return {
Expand All @@ -88,7 +92,7 @@ Environmental Variables can be obtained from `process.env` as usual.

Note that Vite doesn't load `.env` files by default as the files to load can only be determined after evaluating the Vite config, for example, the `root` and `envDir` options affect the loading behaviour. However, you can use the exported `loadEnv` helper to load the specific `.env` file if needed.

```js
```js twoslash
import { defineConfig, loadEnv } from 'vite'

export default defineConfig(({ command, mode }) => {
Expand Down
12 changes: 6 additions & 6 deletions docs/config/server-options.md
Expand Up @@ -18,10 +18,10 @@ The first case is when `localhost` is used. Node.js under v17 reorders the resul

You can set [`dns.setDefaultResultOrder('verbatim')`](https://nodejs.org/api/dns.html#dns_dns_setdefaultresultorder_order) to disable the reordering behavior. Vite will then print the address as `localhost`.

```js
```js twoslash
// vite.config.js
import { defineConfig } from 'vite'
import dns from 'dns'
import dns from 'node:dns'

dns.setDefaultResultOrder('verbatim')

Expand Down Expand Up @@ -238,7 +238,7 @@ Create Vite server in middleware mode.

- **Example:**

```js
```js twoslash
import express from 'express'
import { createServer as createViteServer } from 'vite'

Expand Down Expand Up @@ -358,9 +358,9 @@ export default defineConfig({
// in their paths to the ignore list.
sourcemapIgnoreList(sourcePath, sourcemapPath) {
return sourcePath.includes('node_modules')
}
}
};
},
},
})
```

::: tip Note
Expand Down
2 changes: 1 addition & 1 deletion docs/config/shared-options.md
Expand Up @@ -415,7 +415,7 @@ Adjust console output verbosity. Default is `'info'`.

Use a custom logger to log messages. You can use Vite's `createLogger` API to get the default logger and customize it to, for example, change the message or filter out certain warnings.

```js
```ts twoslash
import { createLogger, defineConfig } from 'vite'

const logger = createLogger()
Expand Down
39 changes: 27 additions & 12 deletions docs/guide/api-hmr.md
Expand Up @@ -8,15 +8,15 @@ The manual HMR API is primarily intended for framework and tooling authors. As a

Vite exposes its manual HMR API via the special `import.meta.hot` object:

```ts
```ts twoslash
import type { ModuleNamespace } from 'vite/types/hot.d.ts'
import type { InferCustomEventPayload } from 'vite/types/customEvent.d.ts'

// ---cut---
interface ImportMeta {
readonly hot?: ViteHotContext
}

type ModuleNamespace = Record<string, any> & {
[Symbol.toStringTag]: 'Module'
}

interface ViteHotContext {
readonly data: any

Expand All @@ -32,7 +32,6 @@ interface ViteHotContext {
prune(cb: (data: any) => void): void
invalidate(message?: string): void

// `InferCustomEventPayload` provides types for built-in Vite events
on<T extends string>(
event: T,
cb: (payload: InferCustomEventPayload<T>) => void,
Expand Down Expand Up @@ -67,7 +66,9 @@ Vite provides type definitions for `import.meta.hot` in [`vite/client.d.ts`](htt
For a module to self-accept, use `import.meta.hot.accept` with a callback which receives the updated module:
```js
```js twoslash
import 'vite/client'
// ---cut---
export const count = 1

if (import.meta.hot) {
Expand All @@ -90,7 +91,13 @@ Vite requires that the call to this function appears as `import.meta.hot.accept(
A module can also accept updates from direct dependencies without reloading itself:
```js
```js twoslash
// @filename: /foo.d.ts
export declare const foo: () => void

// @filename: /example.js
import 'vite/client'
// ---cut---
import { foo } from './foo.js'

foo()
Expand All @@ -117,7 +124,9 @@ if (import.meta.hot) {
A self-accepting module or a module that expects to be accepted by others can use `hot.dispose` to clean-up any persistent side effects created by its updated copy:
```js
```js twoslash
import 'vite/client'
// ---cut---
function setupSideEffect() {}

setupSideEffect()
Expand All @@ -133,7 +142,9 @@ if (import.meta.hot) {
Register a callback that will call when the module is no longer imported on the page. Compared to `hot.dispose`, this can be used if the source code cleans up side-effects by itself on updates and you only need to clean-up when it's removed from the page. Vite currently uses this for `.css` imports.
```js
```js twoslash
import 'vite/client'
// ---cut---
function setupOrReuseSideEffect() {}

setupOrReuseSideEffect()
Expand All @@ -151,7 +162,9 @@ The `import.meta.hot.data` object is persisted across different instances of the
Note that re-assignment of `data` itself is not supported. Instead, you should mutate properties of the `data` object so information added from other handlers are preserved.
```js
```js twoslash
import 'vite/client'
// ---cut---
// ok
import.meta.hot.data.someValue = 'hello'

Expand All @@ -169,7 +182,9 @@ A self-accepting module may realize during runtime that it can't handle a HMR up
Note that you should always call `import.meta.hot.accept` even if you plan to call `invalidate` immediately afterwards, or else the HMR client won't listen for future changes to the self-accepting module. To communicate your intent clearly, we recommend calling `invalidate` within the `accept` callback like so:
```js
```js twoslash
import 'vite/client'
// ---cut---
import.meta.hot.accept((module) => {
// You may use the new module instance to decide whether to invalidate.
if (cannotHandleUpdate(module)) {
Expand Down

0 comments on commit 6f8a320

Please sign in to comment.