使用Shinylive部署含ggplot2依赖的R Shiny应用失败求助
我在demo/app.R文件中有一个简单的演示应用,代码如下:
library(shiny) library(ggplot2) ui <- fluidPage( titlePanel("GGPlot2 Example in Shinylive"), sidebarLayout( sidebarPanel( sliderInput("n", "Number of points:", min = 10, max = 1000, value = 100) ), mainPanel( plotOutput("ggplot") ) ) ) server <- function(input, output, session) { output$ggplot <- renderPlot({ df <- data.frame(x = rnorm(input$n), y = rnorm(input$n)) ggplot(df, aes(x = x, y = y)) + geom_point(color = "steelblue") + theme_minimal() }) } shinyApp(ui = ui, server = server)
使用以下命令部署:
shinylive::export("demo", "demo_site")
然后运行:
httpuv::runStaticServer("demo_site")
应用在浏览器加载时出现错误:
An error has occurred!
package or namespace load failed for ‘ggplot2’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]): there is no package called ‘munsell’
控制台同时出现以下信息:
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.Understand this error.
shinylive.js:32076 WebR is using
PostMessagecommunication channel, nested R REPLs are not available.tn @ shinylive.js:32076Understand this warning
shinylive.js:35463 preload error:wasm streaming compile failed: TypeError: Failed to execute 'compile' on 'WebAssembly': Incorrect response MIME type. Expected 'application/wasm'.
_error @ shinylive.js:35463Understand this error
shinylive.js:35463 preload error:falling back to ArrayBuffer instantiationshinylive.js:35463 preload error:Warning: Error in : package or namespace load failed for ‘ggplot2’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
shinylive.js:35463 preload error:Warning: Error in : package or namespace load failed for ‘ggplot2’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
仅使用R基础图形的演示应用可正常部署,看起来依赖未被打包。请问部署含ggplot2这类额外依赖的Shinylive应用需要哪些额外步骤?
Shinylive默认仅打包R基础包,对于ggplot2这类带有多层嵌套依赖的第三方包,需要手动指定要包含的依赖项,具体操作如下:
获取完整依赖链
先确认ggplot2的所有递归依赖,运行以下命令:tools::package_dependencies("ggplot2", recursive = TRUE)这会列出ggplot2直接和间接依赖的所有包,比如munsell、scales、rlang等。
部署时显式指定依赖包
修改shinylive::export命令,通过packages参数传入所有需要的包。可以手动列出,或者用代码自动获取:# 自动获取所有依赖 required_pkgs <- unlist(tools::package_dependencies("ggplot2", recursive = TRUE)) # 执行导出,包含ggplot2及其所有依赖 shinylive::export( app_dir = "demo", dest_dir = "demo_site", packages = c("ggplot2", required_pkgs) )这样Shinylive会把所有指定的包打包到输出目录中。
验证依赖是否打包成功
部署完成后,检查demo_site/lib目录,确认里面包含所有指定的包文件夹,确保没有遗漏。关于WebAssembly MIME类型警告
控制台中的wasm streaming compile failed属于本地测试的小问题,是因为httpuv服务器未正确设置application/wasm的MIME类型。将应用部署到正式静态服务器(如GitHub Pages、Netlify)时,这个警告会自动消失,本地测试可以忽略。
内容的提问来源于stack exchange,提问作者TheDza

