developing shiny app as a package and deploying it to shiny server
There is already an accepted answer with many votes, but I'd like to add a few things, so I'll answer myself as well. For more information, you can read my article Supplementing your R package with a Shiny app.
This is the folder structure I use:
- mypacakge
|- inst
|- myapp
|- ui.R
|- server.R
|- R
|- runApp.R
|- ...
|- DESCRIPTION
|- ...
Inside the R/
folder is where I place all the non-shiny code. The code for the shiny app itself lives in inst/
. The R/runApp.R
file is defined as
#' @export
runExample <- function() {
appDir <- system.file("myapp", package = "mypackage")
if (appDir == "") {
stop("Could not find myapp. Try re-installing `mypackage`.", call. = FALSE)
}
shiny::runApp(appDir, display.mode = "normal")
}
(You can see this in action; for example, shinyalert uses this structure for its demo app).
In a comment, you asked how can this be deployed on a shiny server. It's simple, you can simply have a file /srv/shiny-server/myapp.app.R
that calls and runs that package (after you've installed the package on the server):
dir <- system.file("myapp", package = "mypackage")
setwd(dir)
shiny::shinyAppDir(".")
(You can see this in action as well, code here)
When I make shiny applications as a stand-alone package, I usually organize the files as so:
In the R directory:
- All of my methods to support the application (these should be exported if they will be used in either the
ui.R
,server.R
, orglobal.R
files) - A
launch_application
function
The definition of launch_application
is similar to:
launch_application <- function(x, ...)
{
shiny::runApp(appDir = system.file("application", package = [my_pkg]),
...)
}
In the inst directory
application/server.R
application/ui.R
application/global.R
After building and installing the package, I then just need to run
library(my_pkg)
launch_application(...)