构建R包时vignettes是否在全新R会话生成?构建机制咨询
Great question—let’s unpack this clearly, since the vignette build process can feel confusing when comparing interactive vs. formal package building workflows.
Do vignettes build in a fresh R session?
It depends on how you’re building them:
- Formal package builds (R CMD build / devtools::build_vignettes): Yes, absolutely. These workflows use a completely fresh, clean R session with no pre-loaded packages beyond base R and your package’s explicit dependencies.
- Interactive knitting (RStudio "Knit" button / manual knitr::knit()): No. This uses your current R console’s environment—including any packages you’ve loaded, objects you’ve created, etc.—which is why you saw your suggested packages already attached.
The Core Build Mechanism
Let’s break down what happens when you use the formal tools like tools::buildVignettes (which devtools::build_vignettes wraps):
- A new, isolated R session is started. This session has no memory of your interactive console’s state.
- Your package is temporarily installed into a sandboxed location (so it doesn’t interfere with your main installed version).
- Only packages listed in your package’s
Importsfield are automatically loaded. Packages inSuggestsare not loaded by default—you have to explicitly calllibrary()orrequire()for them in your vignette code if needed. - The vignette is knitted within this clean environment, ensuring reproducibility and that your vignette only relies on declared dependencies.
devtools::build_vignettes doesn’t reinvent the wheel here—it’s just a convenient wrapper that calls tools::buildVignettes under the hood, adding some quality-of-life checks (like ensuring you have necessary knitting tools installed).
Why You Saw Suggested Packages Loaded
Your test using RStudio’s "Knit" button is an interactive workflow, designed for quick iteration and debugging. It reuses your current console session to save time, which means any packages you’d previously loaded (including suggested ones) are still in the environment. This is great for tweaking vignette code, but it doesn’t reflect how vignettes are built when you release or distribute your package.
How to Test the Formal Build Environment
To verify your vignettes behave correctly in the clean session used by R CMD build:
- Run
devtools::build_vignettes()in your console (this will use the fresh session mechanism). - Or, from your terminal, navigate to your package directory and run
R CMD build .—this will build the entire package, including vignettes in the clean session.
Either of these will replicate the environment that CRAN or other users will see when building your package.
内容的提问来源于stack exchange,提问作者llrs

