Sub topic 12
Declaring dependencies between packages
This chapter assumes you can create an unlocked package and build a package version with the Salesforce CLI. It also assumes you have a Dev Hub and an sfdx-project.json file. Here you will declare that one package needs another and see what the tooling does with that declaration.
Why declare a dependency
Suppose a Sales package contains an Apex class that reads a custom field owned by a Core package. If Sales is installed in an org without Core, the install fails. A declared dependency makes this relationship explicit. The Dev Hub checks it when you build the version, and the install process checks it again in the target org.
Declaring the dependency
Dependencies go in the dependencies array of the dependent package's directory entry. Each entry names a package and a version number.
{
"packageDirectories": [
{
"path": "force-app/core",
"package": "Core",
"versionName": "Initial release",
"versionNumber": "1.0.0.NEXT",
"default": true
},
{
"path": "force-app/sales",
"package": "Sales",
"versionName": "Initial release",
"versionNumber": "1.0.0.NEXT",
"dependencies": [
{ "package": "Core", "versionNumber": "1.0.0.LATEST" }
]
}
],
"namespace": "",
"sfdcLoginUrl": "https://login.salesforce.com",
"sourceApiVersion": "61.0"
}Three rules apply here:
Coreis listed beforeSales. The order ofpackageDirectoriesis the order in which source is deployed, so a dependency must come first.1.0.0.LATESTmeans "the newest build of version 1.0.0". You can also pin an exact build, such as1.0.0.3, or use a package alias like[email protected].- A package can only depend on packages in the same Dev Hub, or on packages that are already released.
What happens at build time
When you run sf package version create --package Sales, the Dev Hub resolves [email protected] to a concrete build and records it with the new Sales version. Installing Sales later pulls in that exact Core build first, if the org does not already have it.
Common errors
- Dependency not found. The
packagename is misspelled, or it has no entry inpackageAliases. Create the package first, so the CLI adds the alias. - Wrong order. If
Salesappears beforeCore, the build fails because the referenced metadata does not exist yet. - Beta dependency in production. A beta
Corebuild can be used in scratch orgs, but production installs need a released version. PromoteCorebefore you promoteSales. - Circular dependency.
Corecannot depend onSalesifSalesdepends onCore. Move the shared metadata into a third package that both can depend on.
Practice
Exercise
A Sales package depends on Core, and you want to install Sales in production. Which versions must be released, and why?
Show answer
Both. Production only accepts released (promoted) versions. Sales needs the exact Core build it was built against, so promote that Core build first, then promote Sales.