### Full Slide Configuration Example Source: https://github.com/antfu/skills/blob/main/skills/slidev/references/core-frontmatter.md An example combining multiple frontmatter options for a comprehensive slide setup. ```yaml --- layout: center background: /bg.jpg class: text-white text-center transition: fade clicks: 3 zoom: 0.9 hideInToc: false --- # Slide Content ``` -------------------------------- ### Using Various Composables in Setup Stores Source: https://github.com/antfu/skills/blob/main/skills/pinia/references/features-composables.md Setup Stores provide more flexibility for using composables. This example integrates `useMediaControls` from `@vueuse/core` to manage video playback. ```typescript import { defineStore } from 'pinia' import { useMediaControls } from '@vueuse/core' import { ref } from 'vue' export const useVideoPlayer = defineStore('video', () => { const videoElement = ref() const src = ref('/data/video.mp4') const { playing, volume, currentTime, togglePictureInPicture } = useMediaControls(videoElement, { src }) function loadVideo(element: HTMLVideoElement, newSrc: string) { videoElement.value = element src.value = newSrc } return { src, playing, volume, currentTime, loadVideo, togglePictureInPicture, } }) ``` -------------------------------- ### Common Workflow: Development Source: https://github.com/antfu/skills/blob/main/skills/nuxt/references/core-cli.md Standard development workflow: install dependencies and start the dev server. ```bash pnpm install pnpm dev # or npx nuxt dev ``` -------------------------------- ### build:prepare Hook Example Source: https://github.com/antfu/skills/blob/main/skills/tsdown/references/advanced-hooks.md Use the `build:prepare` hook to perform setup tasks before the build starts, such as cleaning old files or validating the environment. The context provides build options and hook utilities. ```typescript hooks: { 'build:prepare': async (context) => { console.log('Starting build for:', context.options.entry) await cleanOldFiles() }, } ``` -------------------------------- ### Initialize a New VitePress Project Source: https://github.com/antfu/skills/blob/main/skills/vitepress/references/core-cli.md Starts the setup wizard to initialize a new VitePress project, creating basic file structures like configuration and home page. ```bash vitepress init ``` -------------------------------- ### Pinia Setup Store HMR Example Source: https://github.com/antfu/skills/blob/main/skills/pinia/references/advanced-hmr.md Example of setting up HMR for a Pinia setup store. This allows for stateful edits during development. ```typescript import { defineStore, acceptHMRUpdate } from 'pinia' export const useCounterStore = defineStore('counter', () => { const count = ref(0) const increment = () => count.value++ return { count, increment } }) if (import.meta.hot) { import.meta.hot.accept(acceptHMRUpdate(useCounterStore, import.meta.hot)) } ``` -------------------------------- ### Full Slidev Presentation Template Example Source: https://github.com/antfu/skills/blob/main/skills/slidev/references/core-headmatter.md An example combining multiple configuration options for a complete Slidev presentation setup. ```yaml --- theme: default title: Presentation Title author: Your Name highlighter: shiki lineNumbers: true transition: slide-left aspectRatio: 16/9 canvasWidth: 980 fonts: sans: Roboto mono: Fira Code drawings: enabled: true persist: true download: true --- ``` -------------------------------- ### Basic Usage of useUserMedia Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useUserMedia.md Demonstrates the basic setup for using `useUserMedia` to get a video stream and display it in a video element. It starts the stream automatically and watches for changes to update the video source. ```vue ``` -------------------------------- ### Complete Turborepo CI Workflow Example Source: https://github.com/antfu/skills/blob/main/skills/turborepo/references/ci/github-actions.md A comprehensive GitHub Actions workflow for Turborepo. It includes checkout, Node.js setup with pnpm caching, dependency installation, and running affected builds, tests, and linting commands. ```yaml name: CI on: push: branches: [main] pull_request: branches: [main] jobs: build: runs-on: ubuntu-latest env: TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} TURBO_TEAM: ${{ vars.TURBO_TEAM }} steps: - uses: actions/checkout@v4 with: fetch-depth: 2 - uses: pnpm/action-setup@v3 with: version: 9 - uses: actions/setup-node@v4 with: node-version: 20 cache: "pnpm" - name: Install dependencies run: pnpm install --frozen-lockfile - name: Build run: turbo run build --affected - name: Test run: turbo run test --affected - name: Lint run: turbo run lint --affected ``` -------------------------------- ### Vue 3 Setup with useCookies Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useCookies.md Demonstrates common usage of useCookies in a Vue 3 setup script, including getting, setting, and displaying cookie values. ```vue ``` -------------------------------- ### Basic GitHub Actions CI Setup Source: https://github.com/antfu/skills/blob/main/skills/pnpm/references/best-practices-ci.md A fundamental GitHub Actions workflow for CI that checks out code, sets up pnpm and Node.js, and runs install, test, and build commands. ```yaml name: CI on: [push, pull_request] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 with: version: 9 - uses: actions/setup-node@v4 with: node-version: 20 cache: 'pnpm' - run: pnpm install --frozen-lockfile - run: pnpm test - run: pnpm build ``` -------------------------------- ### Basic useMediaControls Example Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useMediaControls.md Demonstrates basic playback control, volume adjustment, and time seeking for a video element. Requires `useTemplateRef` for element binding and `onMounted` for initial property setup. ```vue ``` -------------------------------- ### Install publint and attw Source: https://github.com/antfu/skills/blob/main/skills/tsdown/references/option-lint.md Install publint and/or @arethetypeswrong/core as development dependencies. ```bash # publint only npm install -D publint # attw only npm install -D @arethetypeswrong/core # both npm install -D publint @arethetypeswrong/core ``` -------------------------------- ### Install all dependencies Source: https://github.com/antfu/skills/blob/main/skills/pnpm/references/core-cli.md Installs all dependencies listed in the package.json. Use `pnpm i` as a shorthand. ```bash pnpm install # or pnpm i ``` -------------------------------- ### Install All Skills Source: https://github.com/antfu/skills/blob/main/README.md Installs all skills from the antfu/skills repository. Use the -g flag to install them globally. ```bash pnpx skills add antfu/skills --skill='*' ``` -------------------------------- ### Compare pnpm Install Times Source: https://github.com/antfu/skills/blob/main/skills/pnpm/references/best-practices-performance.md Benchmark different pnpm installation strategies, including clean installs, frozen lockfile installs, and installs with offline preference. ```bash # Clean install rm -rf node_modules pnpm-lock.yaml time pnpm install # Cached install (with lockfile) rm -rf node_modules time pnpm install --frozen-lockfile # With store cache time pnpm install --frozen-lockfile --prefer-offline ``` -------------------------------- ### Install and Configure Preset Web Fonts Source: https://github.com/antfu/skills/blob/main/skills/unocss/references/preset-web-fonts.md Import and configure the preset with desired fonts. This example sets up Roboto for sans-serif and Fira Code for monospace fonts using Google Fonts. ```typescript import { defineConfig, presetWebFonts, presetWind3 } from 'unocss' export default defineConfig({ presets: [ presetWind3(), presetWebFonts({ provider: 'google', fonts: { sans: 'Roboto', mono: 'Fira Code', }, }), ], }) ``` -------------------------------- ### Installing Dependencies with `pnpm filter` Source: https://github.com/antfu/skills/blob/main/skills/turborepo/references/best-practices/RULE.md Demonstrates the recommended way to install dependencies: directly within the package that requires them using `pnpm add --filter`. Avoid installing general dependencies at the root. ```bash # Good: Install in the package that needs it pnpm add lodash --filter=@repo/utils # Avoid: Installing everything at root pnpm add lodash -w # Only for repo-level tools ``` -------------------------------- ### Install All Skills Globally Source: https://github.com/antfu/skills/blob/main/README.md Installs all skills from the antfu/skills repository globally. This is an alternative to the standard installation. ```bash pnpx skills add antfu/skills --skill='*' -g ``` -------------------------------- ### Complete Example with Directives Source: https://github.com/antfu/skills/blob/main/skills/unocss/references/transformer-directives.md A comprehensive example demonstrating the combined usage of @apply, theme(), @screen, and icon() directives. ```css .card { @apply rounded-lg shadow-md p-4; background-color: theme('colors.white'); } .card-header { @apply 'font-bold text-lg border-b'; padding-bottom: theme('spacing.2'); } @screen md { .card { @apply flex gap-4; } } .card-icon { background-image: icon('i-carbon-document'); @apply w-6 h-6; } ``` -------------------------------- ### Install and Initialize Lint-Staged Source: https://github.com/antfu/skills/blob/main/skills/antfu/references/antfu-eslint-config.md Commands to install lint-staged and simple-git-hooks, and initialize simple-git-hooks. ```bash pnpm add -D lint-staged simple-git-hooks npx simple-git-hooks ``` -------------------------------- ### Basic Script Setup Syntax Source: https://github.com/antfu/skills/blob/main/skills/vue/references/script-setup-macros.md Demonstrates the fundamental structure of a Vue SFC using ` ``` -------------------------------- ### Install focus-trap Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useFocusTrap.md Install the focus-trap library, a peer dependency for useFocusTrap. ```bash npm i focus-trap@^7 ``` -------------------------------- ### Bun Package Manager Setup for CI Source: https://github.com/antfu/skills/blob/main/skills/turborepo/references/ci/github-actions.md Sets up Bun for a GitHub Actions workflow. This snippet installs Bun and then installs project dependencies using 'bun install'. ```yaml - uses: oven-sh/setup-bun@v1 with: bun-version: latest - run: bun install --frozen-lockfile ``` -------------------------------- ### Complete Blog Example Paths Loader Source: https://github.com/antfu/skills/blob/main/skills/vitepress/references/features-dynamic-routes.md A comprehensive example for a blog, reading markdown files, parsing frontmatter with `gray-matter`, and extracting slugs, titles, and dates to generate routes. ```javascript import fs from 'node:fs' import matter from 'gray-matter' export default { watch: ['./posts/*.md'], paths(files) { return files .filter(f => !f.includes('[slug]')) .map(file => { const content = fs.readFileSync(file, 'utf-8') const { data, content: body } = matter(content) const slug = file.match(/([^/]+)\.md$/)[1] return { params: { slug, title: data.title, date: data.date }, content: body } }) } } ``` -------------------------------- ### Vue Script Setup Usage Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useElementSize.md Use `useElementSize` with `useTemplateRef` to get reactive width and height of an element in script setup. ```vue ``` -------------------------------- ### Install drauu Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useDrauu.md Install the drauu library using npm. ```bash npm i drauu@^0 ``` -------------------------------- ### Install Icon Collection Source: https://github.com/antfu/skills/blob/main/skills/slidev/references/code-groups.md Install the necessary Iconify collection for custom icons. ```bash pnpm add @iconify-json/uil ``` -------------------------------- ### Complete Turborepo Configuration Example Source: https://github.com/antfu/skills/blob/main/skills/turborepo/references/environment/RULE.md A comprehensive example demonstrating the configuration of global and task-specific environment variables, including both hashed and pass-through variables. ```json { "$schema": "https://v2-8-18-canary-7.turborepo.dev/schema.json", "globalEnv": ["CI", "NODE_ENV"], "globalPassThroughEnv": ["GITHUB_TOKEN", "NPM_TOKEN"], "tasks": { "build": { "env": ["DATABASE_URL", "API_*"], "passThroughEnv": ["SENTRY_AUTH_TOKEN"] }, "test": { "env": ["TEST_DATABASE_URL"] } } } ``` -------------------------------- ### Install unplugin-solid Source: https://github.com/antfu/skills/blob/main/skills/tsdown/references/recipe-solid.md Install the unplugin-solid package as a development dependency. ```bash npm install -D unplugin-solid ``` -------------------------------- ### Setup useDocumentVisibility in Vue Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useDocumentVisibility.md Import and use the useDocumentVisibility composable in your Vue setup script to get the document's visibility state. ```vue ``` -------------------------------- ### CLI Examples: Basic Watch and Options Source: https://github.com/antfu/skills/blob/main/skills/tsdown/references/option-watch-mode.md Demonstrates common CLI commands for watch mode, including enabling sourcemaps, disabling cleaning, and specifying formats. ```bash # Basic watch tsdown -w # Watch with source maps tsdown -w --sourcemap # Watch without cleaning tsdown -w --no-clean # Watch and run on success tsdown -w --on-success "npm test" # Watch specific format tsdown -w --format esm # Watch with minification tsdown -w --minify # Watch and ignore test files tsdown -w --ignore-watch '**/*.test.ts' ``` -------------------------------- ### CLI Examples for Cleaning Source: https://github.com/antfu/skills/blob/main/skills/tsdown/references/option-cleaning.md Demonstrates various command-line options for controlling output directory cleaning, including default, disabling, and watch mode. ```bash # Default (clean enabled) tsdown # Disable cleaning tsdown --no-clean # Watch mode without cleaning tsdown --watch --no-clean # Multiple formats with cleaning tsdown --format esm,cjs --clean ``` -------------------------------- ### Install Dependencies Source: https://github.com/antfu/skills/blob/main/README.md Install project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Install Playwright Source: https://github.com/antfu/skills/blob/main/skills/vue-testing-best-practices/reference/testing-e2e-playwright-recommended.md Installs Playwright and sets up the initial configuration files and directories for E2E testing. ```bash npm init playwright@latest ``` -------------------------------- ### CLI Examples Source: https://github.com/antfu/skills/blob/main/skills/tsdown/references/option-output-directory.md Various command-line interface examples for tsdown, demonstrating default usage, custom output directories, and combining options. ```bash # Default tsdown # Custom directory tsdown --out-dir build tsdown -d lib # Nested directory tsdown --out-dir dist/lib # With other options tsdown --out-dir build --format esm,cjs --dts ``` -------------------------------- ### Initialize a New Layer with Starter Template Source: https://github.com/antfu/skills/blob/main/skills/nuxt/references/advanced-layers.md Use the Nuxt CLI (`npx nuxi init`) with the `--template layer` option to quickly scaffold a new Nuxt layer project. ```bash npx nuxi init --template layer my-layer ``` -------------------------------- ### Install Preset Wind3 Source: https://github.com/antfu/skills/blob/main/skills/unocss/references/preset-wind3.md Import and configure Preset Wind3 in your UnoCSS setup. ```typescript import { defineConfig, presetWind3 } from 'unocss' export default defineConfig({ presets: [ presetWind3(), ], }) ``` -------------------------------- ### Basic useGamepad Setup Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useGamepad.md Demonstrates the basic setup for using the useGamepad composable to access gamepad information. Ensure user interaction with the page via a gamepad to detect it. ```vue ``` -------------------------------- ### Install and Configure Preset Mini Source: https://github.com/antfu/skills/blob/main/skills/unocss/references/preset-mini.md Import and configure preset-mini in your UnoCSS setup. ```typescript import { defineConfig, presetMini } from 'unocss' export default defineConfig({ presets: [ presetMini(), ], }) ``` -------------------------------- ### Vue Suspense Async Component Example Source: https://github.com/antfu/skills/blob/main/skills/vue/references/advanced-patterns.md Suspense works with components that use `async setup()` or top-level `await` in ` ``` -------------------------------- ### Common Workflow: After Cloning Source: https://github.com/antfu/skills/blob/main/skills/nuxt/references/core-cli.md After cloning a project, install dependencies and prepare types. ```bash pnpm install npx nuxt prepare ``` -------------------------------- ### VueUse onStartTyping Usage Example Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/onStartTyping.md This example demonstrates how to use onStartTyping to auto-focus an input field when the user starts typing anywhere on the page. It requires importing onStartTyping and useTemplateRef from VueUse. ```vue ``` -------------------------------- ### Common Workflow: Production Deployment Source: https://github.com/antfu/skills/blob/main/skills/nuxt/references/core-cli.md Build the project for production and preview locally, or generate for static hosting. ```bash pnpm build pnpm preview ``` ```bash pnpm generate ``` -------------------------------- ### Avoid Circular Dependencies in Store Setup Source: https://github.com/antfu/skills/blob/main/skills/pinia/references/features-composing-stores.md Directly accessing another store's state within the setup function of a Pinia store can lead to infinite loops. This example shows the incorrect approach. ```typescript // ❌ Infinite loop const useX = defineStore('x', () => { const y = useY() y.name // Don't read here! return { name: ref('X') } }) const useY = defineStore('y', () => { const x = useX() x.name // Don't read here! return { name: ref('Y') } }) ``` -------------------------------- ### Library with Multiple Builds Example Source: https://github.com/antfu/skills/blob/main/skills/tsdown/references/option-config-file.md Illustrates setting up separate configurations for Node.js and browser builds of a library. ```typescript export default defineConfig([ // Node.js build { entry: ['src/index.ts'], format: ['esm', 'cjs'], platform: 'node', dts: true, }, // Browser build { entry: ['src/browser.ts'], format: ['iife'], platform: 'browser', globalName: 'MyLib', }, ]) ``` -------------------------------- ### VueUse useTrunc Example Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useTrunc.md Demonstrates how to use the useTrunc function to get the integer part of positive and negative numbers reactively. ```typescript import { useTrunc } from '@vueuse/math' const value1 = ref(0.95) const value2 = ref(-2.34) const result1 = useTrunc(value1) // 0 const result2 = useTrunc(value2) // -2 ``` -------------------------------- ### Destructuring with makeDestructurable Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/makeDestructurable.md Shows how to destructure the entity created by makeDestructurable as both an object and an array. This requires the initial setup from the previous example. ```typescript // @include: main // --- let { foo, bar } = obj let [foo, bar] = obj ``` -------------------------------- ### Update CI/CD Configuration for pnpm Source: https://github.com/antfu/skills/blob/main/skills/pnpm/references/best-practices-migration.md Example of updating CI configuration to use pnpm install and setting the package manager version. ```yaml # Before (npm) - run: npm ci # After (pnpm) - uses: pnpm/action-setup@v4 - run: pnpm install --frozen-lockfile ``` ```json Add to package.json for Corepack: { "packageManager": "pnpm@9.0.0" } ``` -------------------------------- ### React Version Flexibility Example Source: https://github.com/antfu/skills/blob/main/skills/turborepo/references/best-practices/dependencies.md Demonstrates how different packages can specify different versions of the same dependency, showcasing flexibility. ```json // packages/legacy-ui/package.json { "dependencies": { "react": "^17.0.0" } } // packages/ui/package.json { "dependencies": { "react": "^18.0.0" } } ``` -------------------------------- ### TypeScript Example for makeDestructurable Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/makeDestructurable.md Demonstrates how to import and use makeDestructurable with an object and an array to create a combined destructurable entity. Ensure '@vueuse/core' is installed. ```typescript import { makeDestructurable } from '@vueuse/core' const foo = { name: 'foo' } const bar = 1024 const obj = makeDestructurable( { foo, bar } as const, [foo, bar] as const, ) ``` -------------------------------- ### Complete Next.js Turbo Configuration Example Source: https://github.com/antfu/skills/blob/main/skills/turborepo/references/environment/gotchas.md A comprehensive example demonstrating global environment variables, pass-through variables, task-specific environment variables, inputs, and outputs for a Next.js build. ```json { "$schema": "https://v2-8-18-canary-7.turborepo.dev/schema.json", "globalEnv": ["CI", "NODE_ENV", "VERCEL"], "globalPassThroughEnv": ["GITHUB_TOKEN", "VERCEL_URL"], "tasks": { "build": { "dependsOn": ["^build"], "env": ["DATABASE_URL", "NEXT_PUBLIC_*", "!NEXT_PUBLIC_ANALYTICS_ID"], "passThroughEnv": ["SENTRY_AUTH_TOKEN"], "inputs": [ "$TURBO_DEFAULT$", ".env", ".env.local", ".env.production", ".env.production.local" ], "outputs": [".next/**", "!.next/cache/**"] } } } ``` -------------------------------- ### Basic Usage of useMousePressed Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useMousePressed.md Import and use `useMousePressed` to get the reactive `pressed` state. This setup listens to mouse and touch events by default. ```typescript import { useMousePressed } from '@vueuse/core' const { pressed } = useMousePressed() ``` -------------------------------- ### Yarn Package Manager Setup for CI Source: https://github.com/antfu/skills/blob/main/skills/turborepo/references/ci/github-actions.md Configures Yarn for a GitHub Actions workflow. Caching is set to 'yarn' to optimize dependency installation. ```yaml - uses: actions/setup-node@v4 with: node-version: 20 cache: "yarn" - run: yarn install --frozen-lockfile ``` -------------------------------- ### Initialize Vitest Project Setup Source: https://github.com/antfu/skills/blob/main/skills/vitest/references/core-cli.md Use the `vitest init` command to set up Vitest for specific environments, such as browser testing. ```bash vitest init browser # Set up browser testing ``` -------------------------------- ### Run VitePress Dev Server with Options Source: https://github.com/antfu/skills/blob/main/skills/vitepress/references/core-cli.md Starts the VitePress development server, specifying the port and enabling the browser to open automatically on startup. ```bash vitepress dev docs --port 3000 --open ``` -------------------------------- ### Basic useTransition Example Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useTransition.md Define a source value and use useTransition to animate its changes. The transition will start from the current value if the source changes mid-transition. ```typescript import { TransitionPresets, useTransition } from '@vueuse/core' import { shallowRef } from 'vue' const source = shallowRef(0) const output = useTransition(source, { duration: 1000, easing: TransitionPresets.easeInOutCubic, }) ``` -------------------------------- ### Create and Run Slidev Project Source: https://github.com/antfu/skills/blob/main/skills/slidev/SKILL.md Use these commands to create a new Slidev project, start the development server, build a static site, or export to PDF. ```bash pnpm create slidev pnpm run dev pnpm run build pnpm run export ``` -------------------------------- ### Install Internal Workspace Package Source: https://github.com/antfu/skills/blob/main/skills/turborepo/references/best-practices/dependencies.md Example of adding an internal workspace package as a dependency to another package, updating the target package's `package.json`. ```bash # pnpm pnpm add @repo/ui --filter=web # This updates package.json: { "dependencies": { "@repo/ui": "workspace:*" } } ``` -------------------------------- ### Directive Registration with ``` -------------------------------- ### Basic API Route Source: https://github.com/antfu/skills/blob/main/skills/nuxt/references/features-server.md Create a simple API route by defining an exported function in the `server/api/` directory. This example creates a GET endpoint at `/api/hello`. ```APIDOC ## GET /api/hello ### Description Returns a simple JSON message. ### Method GET ### Endpoint /api/hello ### Response #### Success Response (200) - **message** (string) - A greeting message. ``` -------------------------------- ### Import and Use useDevicesList Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useDevicesList.md Import and destructure the `useDevicesList` function to get reactive lists of devices. This is the basic setup for accessing cameras, microphones, and speakers. ```typescript import { useDevicesList } from '@vueuse/core' const { devices, videoInputs: cameras, audioInputs: microphones, audioOutputs: speakers, } = useDevicesList() ``` -------------------------------- ### Import and Use useDevicePixelRatio Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useDevicePixelRatio.md Import the `useDevicePixelRatio` function and use it to get the reactive pixel ratio. This is the basic setup for using the composable in your Vue application. ```typescript import { useDevicePixelRatio } from '@vueuse/core' const { pixelRatio } = useDevicePixelRatio() ``` -------------------------------- ### Quick Migration from npm Source: https://github.com/antfu/skills/blob/main/skills/pnpm/references/best-practices-migration.md Remove npm lockfile and node_modules, then install with pnpm. ```bash rm -rf node_modules package-lock.json pnpm install ``` -------------------------------- ### Composable Helper for Required Injections Source: https://github.com/antfu/skills/blob/main/skills/vue-best-practices/references/plugins.md Create composable functions to wrap required injections, providing clear setup error messages if the plugin is not installed. ```typescript import { inject } from 'vue' import { authKey, type AuthService } from '@/injection-keys' export function useAuth(): AuthService { const auth = inject(authKey) if (!auth) { throw new Error('Auth plugin not installed. Did you forget app.use(authPlugin)?') } return auth } ``` -------------------------------- ### preview Source: https://github.com/antfu/skills/blob/main/skills/vite/references/build-and-ssr.md Starts a local server to preview the production build. Useful for testing the built output. ```APIDOC ## preview ### Description Starts a local server to preview the production build. Useful for testing the built output. ### Method `preview(options?) ### Parameters #### Options - **preview** (object) - Optional - Preview specific options. - **port** (number) - Optional - The port to run the preview server on. - **open** (boolean) - Optional - Whether to open the preview server in the browser automatically. ### Request Example ```ts import { preview } from 'vite' const previewServer = await preview({ preview: { port: 8080, open: true }, }) previewServer.printUrls() ``` ``` -------------------------------- ### CLI Multiple Formats Example Source: https://github.com/antfu/skills/blob/main/skills/tsdown/references/option-minification.md Build with multiple output formats and enable minification using CLI flags. ```bash tsdown --format esm --format cjs --minify ``` -------------------------------- ### jsdom Environment DOM Manipulation Test Source: https://github.com/antfu/skills/blob/main/skills/vitest/references/advanced-environments.md Example test using the jsdom environment to manipulate the DOM and test window APIs. Ensure jsdom is installed. ```typescript // @vitest-environment jsdom test('DOM manipulation', () => { document.body.innerHTML = '
' const app = document.getElementById('app') app.textContent = 'Hello' expect(app.textContent).toBe('Hello') }) test('window APIs', () => { expect(window.location.href).toBeDefined() expect(localStorage).toBeDefined() }) ``` -------------------------------- ### Initialize Pinia and Use Store in SPA Source: https://github.com/antfu/skills/blob/main/skills/pinia/references/best-practices-outside-component.md In Single Page Applications, ensure Pinia is installed before calling stores. This example shows the correct order of operations. ```typescript import { useUserStore } from '@/stores/user' import { createPinia } from 'pinia' import { createApp } from 'vue' import App from './App.vue' // ❌ Fails - pinia not created yet const userStore = useUserStore() const pinia = createPinia() const app = createApp(App) app.use(pinia) // ✅ Works - pinia is active const userStore = useUserStore() ``` -------------------------------- ### useInterval with Controls Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useInterval.md Use useInterval with controls enabled to get access to pause, resume, reset, and isActive functions. The counter starts at 0 and increments every 200ms. ```typescript import { useInterval } from '@vueuse/core' const { counter, reset, pause, resume, isActive } = useInterval(200, { controls: true, }) // Reset counter to 0 reset() // Pause/resume the interval pause() resume() ``` -------------------------------- ### Dynamic Path Generation from Local Files Source: https://github.com/antfu/skills/blob/main/skills/vitepress/references/features-dynamic-routes.md Generates routes dynamically by reading directory contents. This example uses `fs.readdirSync` to get package names from a 'packages' directory. ```javascript import fs from 'node:fs' export default { paths() { return fs.readdirSync('packages').map(pkg => ({ params: { pkg } })) } } ``` -------------------------------- ### Server Plugin for Initialization Source: https://github.com/antfu/skills/blob/main/skills/nuxt/references/features-server.md Shows how to use server plugins to run code once when the server starts, like initializing a database connection and attaching it to requests. ```typescript // server/plugins/db.ts export default defineNitroPlugin((nitroApp) => { // Initialize database connection const db = createDbConnection() // Add to context nitroApp.hooks.hook('request', (event) => { event.context.db = db }) }) ``` -------------------------------- ### Basic Usage of useTimeAgo Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useTimeAgo.md Import and use the `useTimeAgo` composable with a Date object to get a reactive time ago string. This is suitable for script setup in Vue components. ```typescript import { useTimeAgo } from '@vueuse/core' const timeAgo = useTimeAgo(new Date(2021, 0, 1)) ``` -------------------------------- ### Build with Default Configuration Source: https://github.com/antfu/skills/blob/main/skills/tsdown/references/reference-cli.md Executes a build using the default configuration settings. ```bash # Build with default config tsdown ``` -------------------------------- ### Using @tanstack/vue-virtual for list virtualization Source: https://github.com/antfu/skills/blob/main/skills/vue-best-practices/references/perf-virtualize-large-lists.md This example demonstrates how to implement list virtualization using the `@tanstack/vue-virtual` library. It provides a headless approach for virtualization, offering flexibility in rendering. ```vue ``` -------------------------------- ### Define a Custom Vitest Environment Source: https://github.com/antfu/skills/blob/main/skills/vitest/references/advanced-environments.md Create a custom environment by exporting an Environment object. This example defines a 'custom' environment with a setup function that adds a global variable. ```typescript // vitest-environment-custom/index.ts import type { Environment } from 'vitest/runtime' export default ``` -------------------------------- ### CLI: Single Entry Point Source: https://github.com/antfu/skills/blob/main/skills/tsdown/references/option-entry.md Use the CLI to specify a single entry point for bundling. ```bash # Single entry tsdown src/index.ts ``` -------------------------------- ### Framework-Specific Task Outputs Source: https://github.com/antfu/skills/blob/main/skills/turborepo/references/configuration/tasks.md Examples of output configurations for different frameworks and build tools. ```json // Next.js "outputs": [".next/**", "!.next/cache/**"] ``` ```json // Vite "outputs": ["dist/**"] ``` ```json // TypeScript (tsc) "outputs": ["dist/**", "*.tsbuildinfo"] ``` ```json // No file outputs (lint, typecheck) "outputs": [] ``` -------------------------------- ### Server API for Cache Operations Source: https://github.com/antfu/skills/blob/main/skills/nuxt/references/features-server.md This example demonstrates how to set and get data from the server storage within an API route. It uses the `useStorage` composable to access the storage instance. ```typescript // server/api/cache.ts export default defineEventHandler(async (event) => { const storage = useStorage() // Set value await storage.setItem('key', { data: 'value' }) // Get value const data = await storage.getItem('key') return data }) ``` -------------------------------- ### Package.json Setup for Unbundled Library Source: https://github.com/antfu/skills/blob/main/skills/tsdown/references/option-unbundle.md Example package.json configuration for a library built with unbundle mode. It defines main, types, and exports to allow users to import individual modules. ```json { "name": "my-library", "type": "module", "main": "./dist/index.js", "types": "./dist/index.d.ts", "exports": { ".": "./dist/index.js", "./utils/*": "./dist/utils/*.js", "./components/*": "./dist/components/*.js" }, "files": ["dist"] } ``` -------------------------------- ### Vue Component with Script Setup Source: https://github.com/antfu/skills/blob/main/skills/vue/SKILL.md Demonstrates a Vue component using ` ``` -------------------------------- ### CLI Production Build Example Source: https://github.com/antfu/skills/blob/main/skills/tsdown/references/option-minification.md Perform a production build with minification and cleaning enabled using CLI flags. ```bash tsdown --minify --clean ``` -------------------------------- ### VueUse useRound Example Source: https://github.com/antfu/skills/blob/main/skills/vueuse-functions/references/useRound.md Demonstrates how to use the useRound function to reactively round a number. Import useRound and a ref, then pass the ref to useRound to get a computed ref with the rounded value. ```typescript import { useRound } from '@vueuse/math' const value = ref(20.49) const result = useRound(value) // 20 ``` -------------------------------- ### Create Vue Project with tsdown Starter Template Source: https://github.com/antfu/skills/blob/main/skills/tsdown/references/recipe-vue.md Use this command to quickly scaffold a new Vue project with tsdown pre-configured. ```bash npx create-tsdown@latest -t vue ``` -------------------------------- ### Optimized .npmrc Configuration Summary Source: https://github.com/antfu/skills/blob/main/skills/pnpm/references/best-practices-performance.md A consolidated example of an `.npmrc` file with various settings optimized for performance, including install behavior, build optimizations, network settings, and workspace concurrency. ```ini # Install behavior prefer-offline=true auto-install-peers=true # Build optimization side-effects-cache=true # Only build what's necessary onlyBuiltDependencies[]=esbuild onlyBuiltDependencies[]=@swc/core # Network fetch-retries=3 network-concurrency=16 # Workspace workspace-concurrency=4 ``` -------------------------------- ### Introduction Slide Layout Source: https://github.com/antfu/skills/blob/main/skills/slidev/references/core-layouts.md Use the 'intro' layout for introduction slides. ```yaml --- layout: intro --- ``` -------------------------------- ### Good Package Structure Example Source: https://github.com/antfu/skills/blob/main/skills/turborepo/references/best-practices/packages.md Illustrates a well-structured monorepo with packages separated by distinct concerns (UI, utils, auth, etc.). ```treeview packages/ ├── ui/ # Shared UI components ├── utils/ # General utilities ├── auth/ # Authentication logic ├── database/ # Database client/schemas ├── eslint-config/ # ESLint configuration ├── typescript-config/ # TypeScript configuration └── api-client/ # Generated API client ``` -------------------------------- ### Build Options Configuration Source: https://github.com/antfu/skills/blob/main/skills/vitepress/references/core-config.md Sets up source directories, output paths, caching, and build behavior like clean URLs and ignoring dead links. ```typescript export default defineConfig({ // Source files directory (relative to project root) srcDir: './src', // Exclude patterns from source srcExclude: ['**/README.md', '**/TODO.md'], // Output directory outDir: './.vitepress/dist', // Cache directory cacheDir: './.vitepress/cache', // Clean URLs without .html extension (requires server support) cleanUrls: true, // Ignore dead links during build ignoreDeadLinks: true, // Or specific patterns: ignoreDeadLinks: ['/playground', /^https?:::localhost/], // Get last updated timestamp from git lastUpdated: true }) ``` -------------------------------- ### Incorrect Pinia Setup for Store Unit Testing Source: https://github.com/antfu/skills/blob/main/skills/vue-testing-best-practices/reference/testing-pinia-store-setup.md This example demonstrates an issue in store unit testing where no active Pinia instance is set, preventing store actions from being accessed or executed. ```javascript import { useUserStore } from '@/stores/user' // BAD: No active Pinia instance test('user store actions', () => { const store = useUserStore() // ERROR: no active Pinia store.login('john', 'password') }) ``` -------------------------------- ### Incorrect Pinia Setup for Component Testing Source: https://github.com/antfu/skills/blob/main/skills/vue-testing-best-practices/reference/testing-pinia-store-setup.md This example shows a common mistake where Pinia is not provided to the Vue application during component testing, leading to an 'injection Symbol(pinia) not found' error. ```javascript import { mount } from '@vue/test-utils' import UserProfile from './UserProfile.vue' // BAD: Missing Pinia - causes injection error test('displays user name', () => { const wrapper = mount(UserProfile) // ERROR: injection "Symbol(pinia)" not found expect(wrapper.text()).toContain('John') }) ```