MCP HubMCP Hub
Вернуться к навыкам

scaffold-shiny-app

pjt222
Обновлено 2 days ago
8 просмотров
17
2
17
Посмотреть на GitHub
Метаdesigndata

О программе

Этот навык создает основу для новых приложений Shiny на R с тремя вариантами фреймворков: golem для production-пакетов R, rhino для корпоративных проектов или vanilla для быстрых прототипов. Он выполняет инициализацию проекта и создает первый модуль, позволяя разработчикам быстро запускать интерактивные веб-приложения, дашборды или инструменты для исследования данных. Используйте его для создания структурированной основы любого типа проекта Shiny с правильными инструментами и организацией.

Быстрая установка

Claude Code

Рекомендуется
Основной
npx skills add pjt222/agent-almanac -a claude-code
Команда плагинаАльтернативный
/plugin add https://github.com/pjt222/agent-almanac
Git клонированиеАльтернативный
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/scaffold-shiny-app

Скопируйте и вставьте эту команду в Claude Code для установки этого навыка

Документация

Scaffold Shiny App

Create a new Shiny application with production-ready structure using golem, rhino, or vanilla scaffolding.

When to Use

  • Starting a new interactive web application in R
  • Creating a dashboard or data explorer prototype
  • Setting up a production Shiny app as an R package (golem)
  • Bootstrapping an enterprise Shiny project (rhino)

Inputs

  • Required: Application name
  • Required: Framework choice (golem, rhino, or vanilla)
  • Optional: Include module scaffolding (default: yes)
  • Optional: Use renv for dependency management (default: yes)
  • Optional: Deployment target (shinyapps.io, Posit Connect, Docker)

Procedure

Step 1: Choose Framework

Evaluate project requirements to select the framework:

FrameworkBest ForStructure
golemProduction apps shipped as R packagesR package with DESCRIPTION, tests, vignettes
rhinoEnterprise apps with JS/CSS build pipelinebox modules, Sass, JS bundling, rhino::init()
vanillaQuick prototypes and learningSingle app.R or ui.R/server.R pair

Got: Clear framework decision based on project scope and team needs.

If fail: If unsure, default to golem — provides the most structure and can be simplified later. Vanilla is only for throwaway prototypes.

Step 2: Scaffold the Project

Golem Path

golem::create_golem("myapp", package_name = "myapp")

This creates:

myapp/
├── DESCRIPTION
├── NAMESPACE
├── R/
│   ├── app_config.R
│   ├── app_server.R
│   ├── app_ui.R
│   └── run_app.R
├── dev/
│   ├── 01_start.R
│   ├── 02_dev.R
│   ├── 03_deploy.R
│   └── run_dev.R
├── inst/
│   ├── app/www/
│   └── golem-config.yml
├── man/
├── tests/
│   ├── testthat.R
│   └── testthat/
└── vignettes/

Rhino Path

rhino::init("myapp")

This creates:

myapp/
├── app/
│   ├── js/
│   ├── logic/
│   ├── static/
│   ├── styles/
│   ├── view/
│   └── main.R
├── tests/
│   ├── cypress/
│   └── testthat/
├── .github/
├── app.R
├── dependencies.R
├── rhino.yml
└── renv.lock

Vanilla Path

Create app.R:

library(shiny)
library(bslib)

ui <- page_sidebar(
  title = "My App",
  sidebar = sidebar(
    sliderInput("n", "Sample size", 10, 1000, 100)
  ),
  card(
    card_header("Output"),
    plotOutput("plot")
  )
)

server <- function(input, output, session) {
  output$plot <- renderPlot({
    hist(rnorm(input$n), main = "Random Normal")
  })
}

shinyApp(ui, server)

Got: Project directory created with all scaffolding files.

If fail: For golem, ensure golem is installed: install.packages("golem"). For rhino, install from GitHub: remotes::install_github("Appsilon/rhino"). For vanilla, ensure shiny and bslib are installed.

Step 3: Configure Dependencies

Golem/Vanilla

# Initialize renv
renv::init()

# Add core dependencies
usethis::use_package("shiny")
usethis::use_package("bslib")
usethis::use_package("DT")         # if using data tables
usethis::use_package("plotly")     # if using interactive plots

# Snapshot
renv::snapshot()

Rhino

Dependencies are managed in dependencies.R:

# dependencies.R
library(shiny)
library(bslib)
library(DT)

Got: All dependencies recorded in DESCRIPTION (golem) or dependencies.R (rhino) and locked with renv.

If fail: If renv::init() fails, check write permissions. If packages fail to install, check R version compatibility.

Step 4: Create First Module

Golem

golem::add_module(name = "dashboard", with_test = TRUE)

This creates R/mod_dashboard.R and tests/testthat/test-mod_dashboard.R.

Rhino

Create app/view/dashboard.R:

box::use(
  shiny[moduleServer, NS, tagList, h3, plotOutput, renderPlot],
)

#' @export
ui <- function(id) {
  ns <- NS(id)
  tagList(
    h3("Dashboard"),
    plotOutput(ns("plot"))
  )
}

#' @export
server <- function(id) {
  moduleServer(id, function(input, output, session) {
    output$plot <- renderPlot({
      plot(1:10)
    })
  })
}

Vanilla

Add module functions to a separate file R/mod_dashboard.R:

dashboardUI <- function(id) {
  ns <- NS(id)
  tagList(
    h3("Dashboard"),
    plotOutput(ns("plot"))
  )
}

dashboardServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    output$plot <- renderPlot({
      plot(1:10)
    })
  })
}

Got: Module file created with UI and server functions using proper namespacing.

If fail: Ensure the module uses NS(id) for all input/output IDs in the UI function. Without namespacing, IDs collide when the module is used multiple times.

Step 5: Run the Application

# Golem
golem::run_dev()

# Rhino
shiny::runApp()

# Vanilla
shiny::runApp("app.R")

Got: Application launches in the browser without errors.

If fail: Check the R console for error messages. Common issues: missing packages (install them), port already in use (specify a different port with port = 3839), or syntax errors in UI/server code.

Validation

  • Application directory has correct structure for chosen framework
  • shiny::runApp() launches without errors
  • At least one module is scaffolded with UI and server functions
  • Dependencies recorded (DESCRIPTION or dependencies.R)
  • renv.lock captures all package versions
  • Module uses NS(id) for proper namespace isolation

Pitfalls

  • Choosing vanilla for production: Vanilla structure lacks testing infrastructure, documentation, and deployment tooling. Use golem or rhino for anything beyond prototypes.
  • Missing namespace in modules: Every inputId and outputId in a module UI must be wrapped with ns(). Forgetting this causes silent ID collisions.
  • golem without devtools workflow: golem apps are R packages. Use devtools::load_all(), devtools::test(), and devtools::document() — not source().
  • rhino without box: rhino uses box for module imports. Don't fall back to library() calls — use box::use() for explicit imports.

Related Skills

  • build-shiny-module — create reusable Shiny modules with proper namespace isolation
  • test-shiny-app — set up shinytest2 and testServer() tests
  • deploy-shiny-app — deploy to shinyapps.io, Posit Connect, or Docker
  • design-shiny-ui — bslib theming and responsive layout design
  • create-r-package — R package scaffolding (golem apps are R packages)
  • manage-renv-dependencies — detailed renv dependency management

GitHub репозиторий

pjt222/agent-almanac
Путь: i18n/caveman-lite/skills/scaffold-shiny-app
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

Похожие навыки

content-collections

Мета

Этот навык предоставляет проверенную в продакшене настройку для Content Collections — TypeScript-ориентированного инструмента, который преобразует файлы Markdown/MDX в типобезопасные коллекции данных с валидацией Zod. Используйте его при создании блогов, сайтов документации или контентных приложений на Vite + React для обеспечения типобезопасности и автоматической проверки содержимого. Он охватывает всё: от настройки плагина Vite и компиляции MDX до оптимизации развертывания и валидации схем.

Просмотреть навык

polymarket

Мета

Этот навык позволяет разработчикам создавать приложения на платформе прогнозных рынков Polymarket, включая интеграцию с API для торговли и получения рыночных данных. Он также обеспечивает потоковую передачу данных в реальном времени через WebSocket для отслеживания текущих сделок и рыночной активности. Используйте его для реализации торговых стратегий или создания инструментов, обрабатывающих обновления рынка в реальном времени.

Просмотреть навык

creating-opencode-plugins

Мета

Этот навык помогает разработчикам создавать плагины OpenCode, которые подключаются к более чем 25 типам событий, таким как команды, файлы и операции LSP. Он предоставляет структуру плагина, спецификации API событий и шаблоны реализации для модулей на JavaScript/TypeScript. Используйте его, когда вам нужно перехватывать, отслеживать или расширять жизненный цикл ассистента OpenCode AI с помощью пользовательской событийно-ориентированной логики.

Просмотреть навык

sglang

Мета

SGLang — это высокопроизводительный фреймворк для обслуживания больших языковых моделей (LLM), специализирующийся на быстрой структурированной генерации JSON, regex и рабочих процессов агентов с использованием кэширования префиксов RadixAttention. Он обеспечивает значительно более высокую скорость вывода, особенно для задач с повторяющимися префиксами, что делает его идеальным для сложных структурированных результатов и многократных диалогов. Выбирайте SGLang вместо альтернатив, таких как vLLM, когда вам требуется ограниченное декодирование или вы создаете приложения с интенсивным совместным использованием префиксов.

Просмотреть навык