### Initialize and run Preact documentation locally Source: https://github.com/preactjs/preact-www/blob/master/CONTRIBUTING.md Commands to install project dependencies and start the development server. This assumes Node.js is installed and the repository has been cloned. ```bash $ npm install $ npm run dev ``` -------------------------------- ### Scaffold and manage Preact projects with Vite Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/getting-started.md Provides CLI commands to initialize, develop, and build a Preact application using the Vite-powered create-preact tool. ```bash npm init preact ``` ```bash cd my-preact-app npm run dev ``` ```bash npm run build ``` -------------------------------- ### Initialize Preact without build tools Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/getting-started.md Demonstrates how to import Preact directly from a CDN and render content to the DOM without requiring a build step or JSX. ```html ``` -------------------------------- ### Preact Signals Counter Example Source: https://github.com/preactjs/preact-www/blob/master/content/en/blog/introducing-signals.md This example demonstrates how to use Preact Signals to create a reactive counter. It shows the basic setup of signals and computed values, and how they update the UI automatically when their values change. This snippet requires the '@preact/signals' library. ```jsx import { render } from 'preact'; import { signal, computed } from '@preact/signals'; const count = signal(0); const double = computed(() => count.value * 2); function Counter() { return ( ); } render(, document.getElementById('app')); ``` -------------------------------- ### Full Todo List Example with REPL Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/signals.md A complete, runnable example demonstrating the initialization of signals, adding todos, and checking the state. This is suitable for interactive testing. ```jsx import { signal } from '@preact/signals'; const todos = signal([{ text: 'Buy groceries' }, { text: 'Walk the dog' }]); const text = signal(''); function addTodo() { todos.value = [...todos.value, { text: text.value }]; text.value = ''; // Reset input value on add } // Check if our logic works console.log(todos.value); // Logs: [{text: "Buy groceries"}, {text: "Walk the dog"}] // Simulate adding a new todo text.value = 'Tidy up'; addTodo(); // Check that it added the new item and cleared the `text` signal: console.log(todos.value); // Logs: [{text: "Buy groceries"}, {text: "Walk the dog"}, {text: "Tidy up"}] console.log(text.value); // Logs: "" ``` -------------------------------- ### Install signals package Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/signals.md Install the signals package using npm. ```bash npm install @preact/signals ``` -------------------------------- ### Install Enzyme and Preact Adapter Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/unit-testing-with-enzyme.md Installs the necessary Enzyme testing library and the specific adapter for Preact. This is a prerequisite for configuring Enzyme to work with Preact components. ```bash npm install --save-dev enzyme enzyme-adapter-preact-pure ``` -------------------------------- ### Install preact-render-to-string Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/server-side-rendering.md Command to install the necessary package for server-side rendering in Preact projects. ```bash npm install -S preact-render-to-string ``` -------------------------------- ### Use HTM for JSX-like syntax Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/getting-started.md Shows how to use HTM with Preact to write JSX-like syntax using tagged templates, avoiding the need for a transpilation build step. ```html ``` -------------------------------- ### Demonstrate batching behavior with computed signals Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/signals.md Example showing how computed signals behave when accessed inside a batch callback. ```js // --repl import { signal, computed, effect, batch } from '@preact/signals'; const count = signal(0); const double = computed(() => count.value * 2); const triple = computed(() => count.value * 3); effect(() => console.log(double.value, triple.value)); batch(() => { // set `count`, invalidating `double` and `triple`: count.value = 1; // Despite being batched, `double` reflects the new computed value. // However, `triple` will only update once the callback completes. console.log(double.value); // Logs: 2 }); ``` -------------------------------- ### Setup Context Provider in Preact Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/context.md Shows how to wrap components with a Provider to pass a specific value down the component tree. ```jsx import { createContext } from 'preact'; export const Theme = createContext('light'); function App() { return ( ); } ``` -------------------------------- ### Asynchronous Rendering Wait for Example Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/preact-testing-library.md Illustrates the importance of `waitFor` in asynchronous Preact rendering. The first example shows a common mistake of checking the DOM before rendering is complete, while the second demonstrates the correct usage with `waitFor` to ensure updates are flushed. ```jsx test('should increment counter", async () => { render(); fireEvent.click(screen.getByText('Increment')); // WRONG: Preact likely won't have finished rendering here expect(screen.getByText("Current value: 6")).toBeInTheDocument(); }); ``` ```jsx test('should increment counter", async () => { render(); fireEvent.click(screen.getByText('Increment')); await screen.findByText('Current value: 6'); // waits for changed element expect(screen.getByText("Current value: 6")).toBeInTheDocument(); // passes }); ``` -------------------------------- ### Create a reactive state model Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/signals.md Example of using createModel to encapsulate signals, computed values, and actions into a reusable unit. ```js import { signal, computed, createModel } from '@preact/signals'; const CounterModel = createModel((initialCount = 0) => { const count = signal(initialCount); const doubled = computed(() => count.value * 2); return { count, doubled, increment() { count.value++; }, decrement() { count.value--; } }; }); const counter = new CounterModel(5); counter.increment(); console.log(counter.count.value); // 6 ``` -------------------------------- ### Configure Babel for JSX Transpilation Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/getting-started.md This configuration snippet shows how to set up the Babel plugin for transforming JSX syntax into function calls. It specifies the 'pragma' for the JSX function and 'pragmaFrag' for fragment creation. ```json { "plugins": [ [ "@babel/plugin-transform-react-jsx", { "pragma": "h", "pragmaFrag": "Fragment" } ] ] } ``` -------------------------------- ### Alias React to Preact with Import Maps Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/getting-started.md Use HTML ` ``` -------------------------------- ### Hook Call Site Ordering Example Source: https://github.com/preactjs/preact-www/blob/master/content/en/tutorial/04-state.md Provides an example illustrating the concept of call site ordering for hooks within a function component. This demonstrates how `useState` calls are associated with specific 'slots' based on their order, emphasizing why hooks must be called consistently and not conditionally. ```js function User() { const [name, setName] = useState('Bob'); // slot 0 const [age, setAge] = useState(42); // slot 1 const [online, setOnline] = useState(true); // slot 2 } ``` -------------------------------- ### Advanced Prerender API for Customization Source: https://github.com/preactjs/preact-www/blob/master/content/en/blog/prerendering-preset-vite.md This example illustrates advanced usage of the `prerender` function export. It shows how to return custom HTML, additional links to discover, and detailed head elements (like lang attribute, title, and meta tags) for the prerendered document. This allows for fine-grained control over the generated output. ```javascript // src/index.jsx // ... export async function prerender(data) { const { html, links: discoveredLinks } = ssr(); return { html, // Optionally add additional links that should be // prerendered (if they haven't already been -- these will be deduped) links: new Set([...discoveredLinks, '/foo', '/bar']), // Optionally configure and add elements to the "" of // the prerendered HTML document head: { // Sets the "lang" attribute: " lang: 'en', // Sets the title for the current page: "My cool page" title: 'My cool page', // Sets any additional elements you want injected into the "": // // elements: new Set([ { type: 'link', props: { rel: 'stylesheet', href: 'foo.css' } }, { type: 'meta', props: { property: 'og:title', content: 'Social media title' } } ]) } }; } ``` -------------------------------- ### Event Handler Testing Setup Source: https://github.com/preactjs/preact-www/blob/master/content/en/tutorial/02-events.md A utility script used in the tutorial environment to intercept console.log calls and trigger a solution state change. ```js useRealm(function(realm) { var win = realm.globalThis; var prevConsoleLog = win.console.log; win.console.log = function() { solutionCtx.setSolved(true); return prevConsoleLog.apply(win.console, arguments); }; return function() { win.console.log = prevConsoleLog; }; }, []); ``` -------------------------------- ### Computed Signal Dependency Example in JavaScript Source: https://github.com/preactjs/preact-www/blob/master/content/en/blog/signal-boosting.md Demonstrates how the order of dependencies for a computed signal can change based on conditional logic. This example highlights the challenge of maintaining consistent dependency order when using data structures like Sets. ```javascript import { signal, computed } from '@preact/signals-core'; const s1 = signal(0); const s2 = signal(0); const s3 = signal(0); const c = computed(() => { if (s1.value) { s2.value; s3.value; } else { s3.value; s2.value; } }); ``` -------------------------------- ### Correct Key Usage with Stable IDs in Preact Source: https://github.com/preactjs/preact-www/blob/master/content/en/tutorial/08-keys.md Illustrates the recommended approach for using stable, unique IDs as keys in Preact. This example shows how to map over an array of objects, using a unique `id` property for each item's key, ensuring correct reconciliation. ```jsx const todos = [ { id: 1, text: 'wake up' }, { id: 2, text: 'make bed' } ]; export default function ToDos() { return (
    {todos.map(todo => (
  • {todo.text}
  • ))}
); } ``` -------------------------------- ### Setup validation for Preact exercises Source: https://github.com/preactjs/preact-www/blob/master/content/en/tutorial/08-keys.md This script hooks into the Preact options to monitor rendering and verify if the user has successfully completed the task by checking the DOM content. ```javascript useRealm(function(realm) { var out = realm.globalThis.document.body.firstElementChild; var options = require('preact').options; var oldRender = options.__r; var timer; options.__r = function(vnode) { timer = setTimeout(check, 10); if (oldRender) oldRender(vnode); }; function check() { timer = null; var c = out.firstElementChild.children; if ( c.length === 2 && /learn preact/i.test(c[0].textContent) && /make an awesome app/i.test(c[1].textContent) ) { solutionCtx.setSolved(true); } } return () => { options.__r = oldRender; }; }); ``` -------------------------------- ### Configure Basic Import Map for Preact Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/no-build-workflows.md Demonstrates the fundamental setup of an Import Map to resolve bare specifiers to CDN URLs. It includes a complete HTML structure showing how to render a Preact component without a build step. ```html
``` -------------------------------- ### Install and Remove Preact Dependencies Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/upgrade-guide.md Commands to install the core Preact X package and remove the deprecated preact-compat package, which is now integrated into the core. ```bash npm install preact npm remove preact-compat ``` -------------------------------- ### Setup Validation Script for Preact Component Source: https://github.com/preactjs/preact-www/blob/master/content/en/tutorial/03-components.md This JavaScript snippet sets up a testing environment using a realm to monitor component rendering and event handling. It hooks into Preact's internal options to verify that the MyButton component is used and that click events are triggered correctly. ```javascript useRealm(function(realm) { var options = require('preact').options; var win = realm.globalThis; var prevConsoleLog = win.console.log; var hasComponent = false; var check = false; win.console.log = function() { if (hasComponent && check) { solutionCtx.setSolved(true); } return prevConsoleLog.apply(win.console, arguments); }; var e = options.event; options.event = function(e) { if (e.type === 'click') { check = true; setTimeout(() => (check = false)); } }; var r = options.__r; options.__r = function(vnode) { if (typeof vnode.type === 'function' && /MyButton/.test(vnode.type)) { hasComponent = true; } }; return function() { options.event = e; options.__r = r; win.console.log = prevConsoleLog; }; }, []); ``` -------------------------------- ### Preact REPL Implementation Examples Source: https://github.com/preactjs/preact-www/blob/master/content/en/tutorial/02-events.md Provides initial and final code structures for a Preact component, demonstrating the implementation of a click event handler within a functional component. ```jsx import { render } from 'preact'; function App() { return (

Count:

); } render(, document.getElementById('app')); ``` ```jsx import { render } from 'preact'; function App() { const clicked = () => { console.log('hi'); }; return (

Count:

); } render(, document.getElementById('app')); ``` -------------------------------- ### Install Preact Testing Library Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/preact-testing-library.md Installs the Preact adapter for the testing-library. This library requires a DOM environment, which is included by default in Jest or can be added using jsdom for other test runners. ```bash npm install --save-dev @testing-library/preact ``` -------------------------------- ### Setup test environment for synchronized counters Source: https://github.com/preactjs/preact-www/blob/master/content/en/tutorial/06-context.md This script initializes a testing environment to verify that multiple counters remain synchronized. It intercepts Preact events to validate the count values and triggers a solution state when synchronization is confirmed. ```javascript var output = useRef(); function getCounts() { var counts = []; var text = output.current.innerText; var r = /Count:\s*([\w.-]*)/gi; while ((t = r.exec(text))) { var num = Number(t[1]); counts.push(isNaN(num) ? t[1] : num); } return counts; } useResult(function(result) { output.current = result.output; if (getCounts().length !== 3) { console.warn( "It looks like you haven't initialized the `count` value to 0." ); } var timer; var count = 0; var options = require('preact').options; var oe = options.event; options.event = function(e) { if (e.currentTarget.localName !== 'button') return; clearTimeout(timer); timer = setTimeout(function() { var counts = getCounts(); if (counts.length !== 3) { return console.warn('We seem to be missing one of the counters.'); } if (counts[0] !== counts[2] || counts[0] !== counts[1]) { return console.warn("It looks like the counters aren't in sync."); } var solved = counts[0] === ++count; solutionCtx.setSolved(solved); }, 10); if (oe) return oe.apply(this, arguments); }; return function() { options.event = oe; }; }, []); ``` -------------------------------- ### Setup Test Environment for Preact Ref Exercise Source: https://github.com/preactjs/preact-www/blob/master/content/en/tutorial/05-refs.md This JavaScript snippet sets up an environment to monitor DOM interactions, specifically patching the focus method of input elements to track user activity for the tutorial exercise. ```javascript function patch(input) { if (input.__patched) return; input.__patched = true; var old = input.focus; input.focus = function() { solutionCtx.setSolved(true); return old.call(this); }; } useResult(function(result) { var expectedInput; var timer; [].forEach.call(result.output.querySelectorAll('input'), patch); var options = require('preact').options; var oe = options.event; options.event = function(e) { if (e.currentTarget.localName !== 'button') return; clearTimeout(timer); var input = e.currentTarget.parentNode.parentNode.querySelector('input'); expectedInput = input; if (input) patch(input); timer = setTimeout(function() { if (expectedInput === input) { expectedInput = null; } }, 10); if (oe) return oe.apply(this, arguments); }; return function() { options.event = oe; }; }, []); ``` -------------------------------- ### Render a Preact Component to the DOM Source: https://github.com/preactjs/preact-www/blob/master/content/en/tutorial/03-components.md Shows how to render a Preact component into the browser's DOM using the `render` function. This example takes a JSX element representing `MyButton` and mounts it to the `document.body`. It requires importing the `render` function from the 'preact' library. ```jsx import { render } from 'preact'; render(, document.body); ``` -------------------------------- ### Preact Todo List with Signals Source: https://github.com/preactjs/preact-www/blob/master/src/components/controllers/repl/examples/todo-lists/todo-list-signals.txt Implements a Todo list using Preact and Preact Signals for state management. It handles adding new todos, removing existing ones, toggling completion status, and displays the count of completed todos. Dependencies include 'preact' and '@preact/signals'. ```javascript import { render } from 'preact'; import { signal, computed } from '@preact/signals'; const todos = signal([ { text: 'Write my first post', completed: true }, { text: 'Buy new groceries', completed: false }, { text: 'Walk the dog', completed: false } ]); const completedCount = computed( () => todos.value.filter(todo => todo.completed).length ); const newItem = signal(''); function addTodo(e) { e.preventDefault(); todos.value = [...todos.value, { text: newItem.value, completed: false }]; newItem.value = ''; // Reset input value on add } function removeTodo(index) { todos.value.splice(index, 1); todos.value = [...todos.value]; } function TodoList() { const onInput = event => (newItem.value = event.target.value); return (
    {todos.value.map((todo, index) => (
  • {' '}
  • ))}

Completed count: {completedCount.value}

); } render(, document.getElementById('app')); ``` -------------------------------- ### Create a Simple Preact Component Source: https://github.com/preactjs/preact-www/blob/master/content/en/tutorial/03-components.md Defines a basic Preact component named `MyButton` that renders an HTML button element. It accepts a `text` prop to set the button's display content. This component is a fundamental example of how to structure reusable UI elements in Preact. ```jsx function MyButton(props) { return ; } ``` -------------------------------- ### Alias React to Preact in Rollup Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/getting-started.md Use the '@rollup/plugin-alias' plugin in Rollup to alias 'react' and 'react-dom' imports to 'preact/compat'. This plugin should be configured before '@rollup/plugin-node-resolve'. ```javascript import alias from '@rollup/plugin-alias'; module.exports = { plugins: [ alias({ entries: [ { find: 'react', replacement: 'preact/compat' }, { find: 'react-dom/test-utils', replacement: 'preact/test-utils' }, { find: 'react-dom', replacement: 'preact/compat' }, { find: 'react/jsx-runtime', replacement: 'preact/jsx-runtime' } ] }) ] }; ``` -------------------------------- ### Alias React to Preact in Node.js package.json Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/getting-started.md Configure Node.js `package.json` to alias 'react' and 'react-dom' to '@preact/compat'. This method is used when bundler aliases are not applicable, such as in Next.js. ```json { "dependencies": { "react": "npm:@preact/compat", "react-dom": "npm:@preact/compat" } } ``` -------------------------------- ### Alias React to Preact in Parcel Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/getting-started.md Configure Parcel by adding an 'alias' key to your `package.json` file. This maps 'react' and 'react-dom' imports to Preact's compatibility layer. ```json { "alias": { "react": "preact/compat", "react-dom/test-utils": "preact/test-utils", "react-dom": "preact/compat", "react/jsx-runtime": "preact/jsx-runtime" } } ``` -------------------------------- ### Alias React to Preact in Webpack Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/getting-started.md Configure Webpack to alias 'react' and 'react-dom' imports to 'preact/compat'. This allows using React libraries seamlessly with Preact. Ensure 'react-dom' alias is placed after 'react-dom/test-utils'. ```javascript const config = { //... resolve: { alias: { react: 'preact/compat', 'react-dom/test-utils': 'preact/test-utils', 'react-dom': 'preact/compat', // Must be below test-utils 'react/jsx-runtime': 'preact/jsx-runtime' } } }; ``` -------------------------------- ### Implement Async Routing with preact-iso Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/preact-iso.md Demonstrates how to set up a router using LocationProvider, ErrorBoundary, and lazy-loaded components. The router handles asynchronous route transitions by preserving the current view until the new route is ready. ```jsx import { lazy, LocationProvider, ErrorBoundary, Router, Route } from 'preact-iso'; // Synchronous import Home from './routes/home.js'; // Asynchronous (throws a promise) const Profiles = lazy(() => import('./routes/profiles.js')); const Profile = lazy(() => import('./routes/profile.js')); const NotFound = lazy(() => import('./routes/_404.js')); function App() { return ( ); } ``` -------------------------------- ### Alias React to Preact in Jest Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/getting-started.md Configure Jest's `moduleNameMapper` to rewrite module paths, aliasing 'react' and 'react-dom' imports to 'preact/compat'. This ensures Jest uses Preact's compatibility layer. ```json { "moduleNameMapper": { "^react$": "preact/compat", "^react-dom/test-utils$": "preact/test-utils", "^react-dom$": "preact/compat", "^react/jsx-runtime$": "preact/jsx-runtime" } } ``` -------------------------------- ### Type Inference for useContext in Preact Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/typescript.md Shows how Preact's `useContext` hook infers type information from the default object provided to `createContext`. The example illustrates how the `lang` variable correctly gets its type from the context. ```tsx const LanguageContext = createContext({ lang: 'en' }); const Display = () => { // lang will be of type string const { lang } = useContext(LanguageContext); return ( <>

Your selected language: {lang}

); }; ``` -------------------------------- ### Comparing State Management Patterns in Preact Source: https://github.com/preactjs/preact-www/blob/master/content/en/blog/introducing-signals.md Demonstrates the limitations of traditional selector-based and wrapper-based state management patterns compared to the desired direct access approach. ```javascript // Selector based subscription :( function Counter() { const value = useSelector(state => state.count); // ... } // Wrapper function based subscription :( const counterState = new Counter(); const Counter = observe(props => { const value = counterState.count; // ... }); ``` -------------------------------- ### Preact REPL 最终设置:添加点击事件处理程序 Source: https://github.com/preactjs/preact-www/blob/master/content/zh/tutorial/02-events.md 这是 Preact REPL 的最终应用程序设置,为按钮添加了一个 `onClick` 事件处理程序,该处理程序会在点击时在控制台输出 'hi'。 ```jsx import { render } from "preact" function App() { const clicked = () => { console.log('hi') } return (

计数:

) } render(, document.getElementById("app")); ``` -------------------------------- ### Alias React to Preact in TypeScript tsconfig.json Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/getting-started.md Configure `tsconfig.json` (or `jsconfig.json`) to alias 'react' and 'react-dom' to Preact's compat layer. Enabling `skipLibCheck` can resolve potential TypeScript compilation errors from React-specific types. ```json { "compilerOptions": { ... "skipLibCheck": true, "baseUrl": "./", "paths": { "react": ["./node_modules/preact/compat/"], "react/jsx-runtime": ["./node_modules/preact/jsx-runtime"], "react-dom": ["./node_modules/preact/compat/"], "react-dom/*": ["./node_modules/preact/compat/*"] } } } ``` -------------------------------- ### Importing Preact Compat in Preact X Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/whats-new.md Preact X integrates the compatibility layer directly into the core package, accessible via `preact/compat`. This simplifies setup for using React ecosystem libraries, eliminating the need for a separate `preact-compat` installation. The code shows the import change from Preact 8.x to Preact X. ```js // Preact 8.x import React from 'preact-compat'; // Preact X import React from 'preact/compat'; ``` -------------------------------- ### Preact REPL 设置 Realm 以检测控制台日志 Source: https://github.com/preactjs/preact-www/blob/master/content/zh/tutorial/02-events.md 此 JavaScript 代码用于在 Preact REPL 环境中设置一个 Realm,以便检测 `console.log` 调用,并据此标记解决方案为已完成。 ```javascript useRealm(function (realm) { var win = realm.globalThis; var prevConsoleLog = win.console.log; win.console.log = function() { solutionCtx.setSolved(true); return prevConsoleLog.apply(win.console, arguments); }; return function () { win.console.log = prevConsoleLog; }; }, []); ``` -------------------------------- ### Preact: Setup for logging state changes Source: https://github.com/preactjs/preact-www/blob/master/content/en/tutorial/07-side-effects.md This JavaScript code sets up a mechanism to detect when a specific `console.log` message related to 'Count is now' and a state value of 1 is triggered. It temporarily overrides `console.log` to check for this condition and signals a solved state if met. This is used in conjunction with the Preact component examples to verify the correct implementation of side effects. ```js useRealm(function(realm) { var win = realm.globalThis; var prevConsoleLog = win.console.log; win.console.log = function(m, s) { if (/Count is now/.test(m) && s === 1) { solutionCtx.setSolved(true); } return prevConsoleLog.apply(win.console, arguments); }; return function() { win.console.log = prevConsoleLog; }; }, []); ``` -------------------------------- ### Preact REPL 初始设置 Source: https://github.com/preactjs/preact-www/blob/master/content/zh/tutorial/02-events.md 这是 Preact REPL 的初始应用程序设置,包含一个简单的 App 组件,其中有一个段落和一个按钮。 ```jsx import { render } from "preact" function App() { return (

计数:

) } render(, document.getElementById("app")); ``` -------------------------------- ### action(fn) Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/signals.md Wrap a function to execute it in a batched and untracked context, suitable for standalone actions. ```APIDOC ## action(fn) ### Description The `action(fn)` function wraps a function to run in a batched and untracked context. This is useful when you need to create standalone actions outside of a model: ### Example ```js import { signal, action } from '@preact/signals'; const count = signal(0); const incrementBy = action((amount) => { count.value += amount; }); incrementBy(5); // Batched update ``` ``` -------------------------------- ### Example Preact Counter Component Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/unit-testing-with-enzyme.md A simple Preact component demonstrating state management with `useState` and a button to increment a counter. This component serves as an example for unit testing. ```jsx import { h } from 'preact'; import { useState } from 'preact/hooks'; export default function Counter({ initialCount }) { const [count, setCount] = useState(initialCount); const increment = () => setCount(count + 1); return (
Current value: {count}
); } ``` -------------------------------- ### Create models with createModel() Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/signals.md Defines a model constructor that encapsulates signals, computed values, and actions. ```js import { signal, computed, effect, createModel } from '@preact/signals'; const CounterModel = createModel((initialCount = 0) => { const count = signal(initialCount); const doubled = computed(() => count.value * 2); effect(() => { console.log('Count changed:', count.value); }); return { count, doubled, increment() { count.value++; }, decrement() { count.value--; } }; }); // Create a new model instance using `new` const counter = new CounterModel(5); counter.increment(); // Updates are automatically batched console.log(counter.count.value); // 6 console.log(counter.doubled.value); // 12 // Clean up all effects when done counter[Symbol.dispose](); ``` -------------------------------- ### Styled Component Example Source: https://github.com/preactjs/preact-www/blob/master/content/en/tutorial/01-vdom.md An example of a component utilizing inline styles and nested HTML elements. It demonstrates passing a CSS object to the style prop and wrapping text in emphasis tags. ```jsx import { createElement, render } from 'preact'; function App() { return (

Hello World!

); } render(, document.getElementById('app')); ``` -------------------------------- ### Configure Webpack for Server and Client Source: https://github.com/preactjs/preact-www/blob/master/content/en/blog/simplifying-islands-arch.md Webpack configurations for building the server-side bundle and generating a manifest file for client-side entry points. ```javascript // webpack.config.server.js const path = require('path'); const nodeExternals = require('webpack-node-externals'); module.exports = { mode: process.env.NODE_ENV != 'production' ? 'development' : 'production', target: 'node', entry: path.resolve(__dirname, './src/server/app.js'), output: { filename: 'server.js', path: path.resolve(__dirname, './dist') }, module: { rules: [{ test: /\.jsx?$/, loader: 'babel-loader' }] }, externals: [nodeExternals()] }; // webpack.config.client.js snippet new WebpackManifestPlugin({ publicPath: '', basePath: '', filter: file => /\.mount\.js$/.test(file.name) }); ``` -------------------------------- ### Handling Internationalized Text in Preact Tests Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/preact-testing-library.md Illustrates a workaround for testing components with frequently changing or internationalized text content. It involves snapshotting translated text to maintain test stability while allowing for easy updates. The example shows finding an element by role and accessible name, similar to the previous example, but using a translated string. ```jsx test('should be able to sign in', async () => { render(); // We can use our translation function directly in the test const label = translate('signinpage.label', 'en-US'); // Snapshot the result so we know what's going on expect(label).toMatchInlineSnapshot(`Sign In`); const field = await screen.findByRole('textbox', { name: label }); fireEvent.change(field, { value: 'user123' }); }); ``` -------------------------------- ### Wrap actions with action() Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/signals.md Wraps a function to execute in a batched and untracked context. ```js import { signal, action } from '@preact/signals'; const count = signal(0); const incrementBy = action((amount) => { count.value += amount; }); incrementBy(5); // Batched update ``` -------------------------------- ### Implement Todo list with useEffect and useState Source: https://github.com/preactjs/preact-www/blob/master/content/en/tutorial/08-keys.md Provides the initial boilerplate and the final solution for fetching todos asynchronously and rendering them as a list in Preact. ```jsx import { render } from 'preact'; import { useState, useEffect } from 'preact/hooks'; const wait = ms => new Promise(r => setTimeout(r, ms)); const getTodos = async () => { await wait(500); return [ { id: 1, text: 'learn Preact', done: false }, { id: 2, text: 'make an awesome app', done: false } ]; }; function TodoList() { const [todos, setTodos] = useState([]); useEffect(() => { getTodos().then(todos => { setTodos(todos); }); }, []); return (
    {todos.map(todo => (
  • {todo.text}
  • ))}
); } render(, document.getElementById('app')); ``` -------------------------------- ### Create and Compose Models with Preact Signals Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/signals.md Demonstrates creating reusable models with factory functions and composing them. Parent model disposal automatically cleans up effects from nested models. ```javascript const TodoItemModel = createModel((text) => { const completed = signal(false); return { text, completed, toggle() { completed.value = !completed.value; } }; }); const TodoListModel = createModel(() => { const items = signal([]); return { items, addTodo(text) { const todo = new TodoItemModel(text); items.value = [...items.value, todo]; }, removeTodo(todo) { items.value = items.value.filter(t => t !== todo); todo[Symbol.dispose](); } }; }); const todoList = new TodoListModel(); todoList.addTodo('Buy groceries'); todoList.addTodo('Walk the dog'); // Disposing the parent also cleans up all nested model effects todoList[Symbol.dispose](); ``` -------------------------------- ### Switch to Hydrate and Export Prerender Function Source: https://github.com/preactjs/preact-www/blob/master/content/en/blog/prerendering-preset-vite.md This JavaScript snippet updates the application's entry point (`src/index.jsx`). It replaces `render` with `hydrate` from `preact-iso` for efficient client-side rendering on prerendered HTML and exports an asynchronous `prerender` function. The `prerender` function is responsible for generating the HTML content during the build process. ```javascript import { hydrate, prerender as ssr } from 'preact-iso'; function App() { return

Hello World!

} if (typeof window !== 'undefined') { hydrate(, document.getElementById('app')); } export async function prerender(data) { return await ssr() } ``` -------------------------------- ### Define Routes with Preact-ISO Router Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/preact-iso.md Demonstrates how to configure routing within a Preact application using the LocationProvider, Router, and Route components from preact-iso. It shows equivalent ways to define routes and includes a catch-all 'NotFound' route. ```jsx import { LocationProvider, Router, Route } from 'preact-iso'; function App() { return ( {/* Both of these are equivalent */} ); } ``` -------------------------------- ### Handle Router Lifecycle Events Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/preact-iso.md Demonstrates how to use Router props like onRouteChange, onLoadStart, and onLoadEnd to track navigation and loading states within a preact-iso application. ```jsx import { LocationProvider, Router } from 'preact-iso'; function App() { return ( console.log('Route changed to', url)} onLoadStart={url => console.log('Starting to load', url)} onLoadEnd={url => console.log('Finished loading', url)} > ); } ``` -------------------------------- ### Preact Counter Component Example Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/preact-testing-library.md A simple Preact component that displays a counter and a button to increment it. It uses the useState hook for managing the count state. ```jsx import { h } from 'preact'; import { useState } from 'preact/hooks'; export function Counter({ initialCount }) { const [count, setCount] = useState(initialCount); const increment = () => setCount(count + 1); return (
Current value: {count}
); } ``` -------------------------------- ### Using a Preact Component in JSX Source: https://github.com/preactjs/preact-www/blob/master/content/en/tutorial/03-components.md Demonstrates how to use a custom Preact component (`MyButton`) within JSX, passing properties to it. It also shows the equivalent `createElement` call, illustrating how JSX is transpiled. This highlights the declarative nature of Preact development. ```js let vdom = ; // remember createElement? here's what the line above compiles to: let vdom = createElement(MyButton, { text: 'Click Me!' }); ``` -------------------------------- ### Server-side Rendering Middleware Source: https://github.com/preactjs/preact-www/blob/master/content/en/blog/simplifying-islands-arch.md Example of an Express middleware that adds a render helper to the response object, allowing for server-side rendering of Preact components to strings. ```javascript app.use((req, res, next) => { res.render = (comp, data) => { return res.write(preactRenderToString(h(comp, { ...data }))); }; }); const handler = (req, res) => { return res.status(200).render(Homepage, { username: 'reaper' }); }; ``` -------------------------------- ### Use Custom Elements in Markdown Source: https://github.com/preactjs/preact-www/blob/master/CONTRIBUTING.md Example of embedding Preact components directly into Markdown files. These components are defined in the project source and rendered via preact-markup. ```markdown ## Example Page

Preact

``` -------------------------------- ### Import Map for Preact Ecosystem Source: https://github.com/preactjs/preact-www/blob/master/content/en/guide/v10/no-build-workflows.md A configuration pattern for including Preact, Hooks, Signals, and HTM. It demonstrates how to map package paths and use the external query parameter to ensure Preact remains a singleton. ```html ```