Token导航 LogoToken导航TokenDH.com
开发规范操作浏览器github未标认证来源可访问许可证需确认审计通过

solid-js-best-practices扎实的 js 最佳实践

Agent Skill

solid-js-best-practices 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

873

周安装

36

GitHub Stars

1

下载量

285
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:solid-js-best-practices(扎实的 js 最佳实践)
来源仓库:https://github.com/richardcarls/solid-js-best-practices
仓库路径:skills/solid-js-best-practices
安装命令:
npx skills add https://github.com/richardcarls/solid-js-best-practices --skill solid-js-best-practices
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/richardcarls/solid-js-best-practices --skill solid-js-best-practices

简介

solid-js-best-practices 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中围绕仓库状态、代码变更或协作事项进行整理。
  • 通过 npx skills add 命令从指定 GitHub 仓库安装使用。
  • 安装前需确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写操作。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Solid.js Best Practices

Comprehensive best practices for building Solid.js applications and components, optimized for AI-assisted code generation, review, and refactoring.

Quick Reference

Essential Imports

import {
  createSignal,
  createEffect,
  createMemo,
  createResource,
  onMount,
  onCleanup,
  Show,
  For,
  Switch,
  Match,
  Index,
  Suspense,
  ErrorBoundary,
  lazy,
  batch,
  untrack,
  mergeProps,
  splitProps,
  children,
} from "solid-js";

import { createStore, produce, reconcile } from "solid-js/store";

Component Skeleton

import { Component, JSX, mergeProps, splitProps } from "solid-js";

interface MyComponentProps {
  title: string;
  count?: number;
  onAction?: () => void;
  children?: JSX.Element;
}

const MyComponent: Component<MyComponentProps> = (props) => {
  // Merge default props
  const merged = mergeProps({ count: 0 }, props);

  // Split component props from passed-through props
  const [local, others] = splitProps(merged, ["title", "count", "onAction"]);

  // Local reactive state
  const [value, setValue] = createSignal("");

  // Derived/computed values
  const doubled = createMemo(() => local.count * 2);

  // Side effects
  createEffect(() => {
    console.log("Count changed:", local.count);
  });

  // Lifecycle
  onMount(() => {
    console.log("Component mounted");
  });

  onCleanup(() => {
    console.log("Component cleanup");
  });

  return (
    <div {...others}>
      <h1>{local.title}</h1>
      <p>Count: {local.count}, Doubled: {doubled()}</p>
      <input
        value={value()}
        onInput={(e) => setValue(e.currentTarget.value)}
      />
      <button onClick={local.onAction}>Action</button>
      {props.children}
    </div>
  );
};

export default MyComponent;

Rules by Category

1. Reactivity (7 rules)

#RulePriorityDescription
1-1Use Signals CorrectlyCRITICALAlways call signals as functions count() not count
1-2Use Memo for Derived ValuesHIGHUse createMemo for computed values, not createEffect
1-3Effects for Side Effects OnlyHIGHUse createEffect only for side effects, not derivations
1-7No Primitives in Reactive ContextsHIGHDon't call hooks or create reactive primitives inside effects or memos
1-4Avoid Setting Signals in EffectsMEDIUMSetting signals in effects can cause infinite loops
1-5Use Untrack When NeededMEDIUMUse untrack() to prevent unwanted reactive subscriptions
1-6Batch Signal UpdatesLOWUse batch() for multiple synchronous signal updates

2. Components (10 rules)

#RulePriorityDescription
2-1Never Destructure PropsCRITICALDestructuring props breaks reactivity
2-6Components Return OnceCRITICALNever use early returns — use <Show>, <Switch>, etc. in JSX
2-9Never Call Components as FunctionsCRITICALAlways use JSX or createComponent() — direct calls leak reactive scope
2-2Use mergePropsHIGHUse mergeProps for default prop values
2-3Use splitPropsHIGHUse splitProps to separate prop groups safely
2-7No React-Specific PropsHIGHUse class not className, for not htmlFor
2-10Custom Element TypeScript DeclarationsHIGHDeclare custom element tags in JSX namespace; augment DOM types for newer attributes
2-4Use children HelperMEDIUMUse children() helper for safe children access
2-5Prefer CompositionMEDIUMPrefer composition and context over prop drilling
2-8Style Prop ConventionsMEDIUMUse object syntax with kebab-case properties for style

3. Control Flow (6 rules)

#RulePriorityDescription
3-1Use Show for ConditionalsHIGHUse <Show> instead of ternary operators
3-2Use For for ListsHIGHUse <For> for referentially-keyed list rendering
3-3Use Index for PrimitivesMEDIUMUse <Index> when array index matters more than identity
3-4Use Switch/MatchMEDIUMUse <Switch>/<Match> for multiple conditions
3-6Stable Component MountMEDIUMAvoid rendering the same component in multiple Switch/Show branches
3-5Provide FallbacksLOWAlways provide fallback props for loading states

4. State Management (5 rules)

#RulePriorityDescription
4-1Signals vs StoresHIGHUse signals for primitives, stores for nested objects
4-2Use Store Path SyntaxHIGHUse path syntax for granular, efficient store updates
4-3Use produce for MutationsMEDIUMUse produce for complex mutable-style store updates
4-4Use reconcile for Server DataMEDIUMUse reconcile when integrating server/external data
4-5Use Context for Global StateMEDIUMUse Context API for cross-component shared state

5. Refs & DOM (7 rules)

#RulePriorityDescription
5-1Use Refs CorrectlyHIGHUse callback refs for conditional elements
5-2Access DOM in onMountHIGHAccess DOM elements in onMount, not during render
5-3Cleanup with onCleanupHIGHAlways clean up subscriptions and timers
5-5Avoid innerHTMLHIGHAvoid innerHTML to prevent XSS — use JSX or textContent
5-7Web Component Controlled StateHIGHUse createEffect + ref + imperative calls to sync signals to web component APIs
5-4Use DirectivesMEDIUMUse use: directives for reusable element behaviors
5-6Event Handler PatternsMEDIUMUse on:/oncapture: namespaces and array handler syntax correctly

6. Performance (6 rules)

#RulePriorityDescription
6-1Avoid Unnecessary TrackingHIGHDon't access signals outside reactive contexts
6-2Use Lazy ComponentsMEDIUMUse lazy() for code splitting large components
6-3Use SuspenseMEDIUMUse <Suspense> for async loading boundaries
6-6Web Component CSS and Bundle StrategyMEDIUMImport components individually; place ::part() overrides in a global stylesheet
6-4Optimize Store AccessLOWAccess only the store properties you need
6-5Prefer classListLOWUse classList prop for conditional class toggling

7. Accessibility (3 rules)

#RulePriorityDescription
7-1Use Semantic HTMLHIGHUse appropriate semantic HTML elements
7-2Use ARIA AttributesMEDIUMApply appropriate ARIA attributes for custom controls
7-3Support Keyboard NavigationMEDIUMEnsure all interactive elements are keyboard accessible

8. Testing (11 rules)

#RulePriorityDescription
8-1Configure Vitest for SolidCRITICALConfigure Vitest with Solid-specific resolve conditions and plugin
8-2Wrap Render in Arrow FunctionsCRITICALAlways use render(() => <C />) not render(<C />)
8-3Test Primitives in a RootHIGHWrap signal/effect/memo tests in createRoot or renderHook
8-4Handle Async in TestsHIGHUse findBy queries and proper timer config for async behavior
8-5Use Accessible QueriesMEDIUMPrefer role and label queries over test IDs
8-6Separate Logic from UI TestsMEDIUMTest primitives/hooks independently from component rendering
8-7Browser Mode for Web Components and PWA APIsHIGHUse Vitest browser mode (real Chromium) for custom elements, shadow DOM, and browser-native APIs
8-8Testing Headless UI Libraries with Non-Standard ARIAMEDIUMHeadless UI libraries use non-obvious ARIA structures and portals — inspect the actual tree before querying
8-9Browser-Native API Test IsolationHIGHClear IndexedDB and localStorage between tests — close connection before deleteDatabase
8-10Router Integration TestingHIGHUse MemoryRouter root prop to provide router context to layout providers
8-11TanStack Query Test SetupHIGHCreate a fresh QueryClient per test with retry and caching disabled

Task-Based Rule Selection

Writing New Components

Load these rules when creating new Solid.js components:

RuleWhy
1-1Ensure signals are called as functions
2-1Prevent reactivity breakage
2-6No early returns — use control flow in JSX
2-9Never call components as plain functions
2-2Handle default props correctly
2-3Separate local and forwarded props
3-1Proper conditional rendering
3-2Efficient list rendering
5-3Prevent memory leaks

Code Review

Focus on these rules during code review:

PriorityRules
CRITICAL1-1, 2-1, 2-6, 2-9
HIGH1-2, 1-3, 1-7, 2-7, 5-2, 5-3, 5-5

Performance Optimization

Load these rules when optimizing performance:

RuleFocus
1-2Prevent unnecessary recomputation
1-6Reduce update cycles
4-2Granular store updates
6-1Prevent unwanted subscriptions
6-2Code splitting
6-4Efficient store access

State Management

Load these rules when working with application state:

RuleFocus
4-1Choose the right primitive
4-2Efficient updates
4-3Complex mutations
4-4External data integration
4-5Cross-component state

Accessibility Audit

Load these rules when auditing accessibility:

RuleFocus
7-1Semantic structure
7-2Screen reader support
7-3Keyboard users

Writing Tests

Load these rules when writing or reviewing tests:

RuleFocus
8-1Correct Vitest configuration
8-2Reactive render scope
8-3Reactive ownership for primitives
8-4Async queries and timers
8-5Accessible query selection
8-6Test architecture
8-7When to use browser mode vs jsdom
8-8Portals and non-standard ARIA structures
8-9IDB and localStorage cleanup patterns
8-10MemoryRouter setup for integration tests
8-11QueryClient configuration for tests

Integrating Web Components / Custom Elements

Load these rules when using any custom element library (Shoelace, FAST, Lion, Material Web Components, etc.) or native browser APIs like <dialog> and the Popover API:

RuleWhy
2-10Declare custom element tags in JSX namespace; type newer HTML attributes and experimental CSS properties
5-6Use on: for all custom element events; type CustomEvent payloads correctly
5-7Sync Solid signals to web component / native browser API imperative calls
6-6Per-component imports for tree-shaking; ::part() overrides in global CSS only

Common Mistakes to Catch

MistakeRuleSolution
Forgetting () on signal access1-1Always call signals: count()
Destructuring props2-1Access via props.name
Using ternaries for conditionals3-1Use <Show> component
.map() for lists3-2Use <For> component
Deriving values in effects1-2Use createMemo
Setting signals in effects1-4Use createMemo or external triggers
Accessing DOM during render5-2Use onMount
Forgetting cleanup5-3Use onCleanup
Early returns in components2-6Use <Show>, <Switch> in JSX instead
Using className or htmlFor2-7Use class and for (standard HTML)
style="color: red" or camelCase styles2-8Use style={{color: "red"}} with kebab-case
Using innerHTML with user data5-5Use JSX or sanitize with DOMPurify
Spreading whole store6-4Access specific properties
String concatenation for class toggling6-5Use classList={{active: isActive()}}
render(<Comp />) without arrow8-2Use render(() => <Comp />)
Effects in tests without owner8-3Wrap in createRoot or use renderHook
getBy for async content8-4Use findBy queries
MyComp(props) instead of <MyComp />2-9Always use JSX syntax or createComponent()
Calling useMatch()/useQuery() inside createEffect/createComputed1-7Call hooks once at component init, not inside reactive computations
Same component in Switch fallback and Match branch3-6Keep component in one stable position; use CSS for layout changes
Custom elements don't upgrade / lifecycle doesn't fire in tests8-7Use Vitest browser mode (real Chromium) instead of jsdom
IDB state persists between tests causing order-dependent failures8-9Close connection before deleteDatabase; use useCleanDb()
Router primitives throw "can only be used inside a Route"8-10Use MemoryRouter root prop with a layout factory
QueryClient retries mask errors / cache leaks between tests8-11Use makeTestQueryClient() with retry: false, gcTime: 0
waitFor(length === 0) passes before data loads8-4Use a settled anchor with findBy before asserting absence
getByRole('form') throws even though the form exists7-2Add aria-label or aria-labelledby to expose role="form"
<my-element onMyChange={...}> misses all events5-6Use on:my-changeon: prefix required for all web component custom events
my-element::part(...) rule inside a .module.css is silently ignored6-6Move ::part() overrides to a non-module global stylesheet
Barrel import of entire web component library6-6Import individual components by path to enable tree-shaking
value={signal()} on web component — no two-way sync5-7Listen to change events; push value imperatively via ref + createEffect
<div popover> or <button popoverTarget="x"> TypeScript error2-10Augment HTMLElement / HTMLButtonElement in a .d.ts file
Object/array prop on custom element becomes "[object Object]"5-7Use prop:myProp={value()} to set a JS property, not an HTML attribute
Experimental CSS property (anchor-name) produces a TypeScript error2-8Cast with as unknown as JSX.CSSProperties instead of as never

Solid.js vs React Mental Model

When helping users familiar with React, keep these differences in mind:

ReactSolid.js
Components re-render on state changeComponents run once, signals update DOM directly
useState returns [value, setter]createSignal returns [getter, setter]
useMemo with deps arraycreateMemo with automatic tracking
useEffect(fn, [deps])createEffect(fn) (no deps array — automatic tracking)
Destructure props freelyNever destructure props
Early returns (if (!x) return null)<Show> / <Switch> in JSX (components return once)
{condition && <Component />}<Show when={condition}><Component /></Show>
{items.map(item =>...)}<For each={items}>{item =>...}</For>
classNameclass
htmlForfor
style={{fontSize: 14}}style={{"font-size": "14px"}}
Context requires useContext hookContext works with useContext or direct access
React 18: ref + addEventListener for custom element events; React 19: onMyEvent={handler} nativelyon:my-event={handler} — always use on: prefix with web component events

Priority Levels

  • CRITICAL: Fix immediately. Causes bugs, broken reactivity, or runtime errors.
  • HIGH: Address in code reviews. Important for correctness and maintainability.
  • MEDIUM: Apply when relevant. Improves code quality and performance.
  • LOW: Consider during refactoring. Nice-to-have optimizations.

Key Solid.js Concepts

Fine-Grained Reactivity

Solid.js updates only the specific DOM elements that depend on changed data, not entire component trees. This is achieved through:

  • Signals: Reactive primitives that track dependencies
  • Effects: Side effects that automatically re-run when dependencies change
  • Memos: Cached derived values that only recompute when dependencies change

Components Render Once

Unlike React, Solid components are functions that run once during initial render. Reactivity happens at the signal level, not the component level. This is why:

  • Props must not be destructured (would capture static values)
  • Signals must be called as functions (to maintain reactive tracking)
  • Control flow uses special components (<Show>, <For>) instead of JS expressions

Stores for Complex State

For nested objects and arrays, Solid provides stores with:

  • Fine-grained updates via path syntax
  • Automatic proxy wrapping for nested reactivity
  • Utilities like produce and reconcile for common patterns

Tooling

For automated linting alongside these best practices, use eslint-plugin-solid. The plugin catches many of the same issues this skill covers (destructured props, early returns, React-specific props, innerHTML usage, style prop format, etc.) and provides auto-fixable rules.

Resources

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

36.76%
按下载量换算105

Claude

28.67%
按下载量换算82

Cursor

20.73%
按下载量换算59

Gemini CLI

8.99%
按下载量换算26

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills