Sub topic 7
Create a Salesforce DX project
This chapter assumes you have installed the sf CLI, can run commands in a terminal, and understand what Salesforce metadata and Apex are. You do not need an authorized org to generate a project, but you will need one in the next chapter to deploy it.
What a Salesforce DX project is
A Salesforce DX project is a local folder with a known layout and a configuration file named sfdx-project.json. The CLI uses that layout to find your source files. Version control tools use the same layout to track changes. The project is the source of truth for your metadata, and orgs are places where you deploy it.
This is different from working only in an org. In an org-centered workflow, the org holds the only copy of your customizations. In a source-driven workflow, your files in version control are the main copy, and you push them to orgs when needed.
Generate a project
Use sf project generate to create the folder and its starting files.
sf project generate --name myproject
cd myprojectThe --name flag sets the project folder name. The command creates a directory with that name in your current location. It does not need an org, so it works before you log in.
The command also accepts a --template flag. The default template is standard, which is the one this tutorial uses. Run sf project generate --help to see the other templates and flags available in your installed version.
What you get
The standard template creates a layout like this:
myproject/
├── .forceignore
├── .gitignore
├── .prettierrc
├── .vscode/
├── config/
│ └── project-scratch-def.json
├── force-app/
│ └── main/
│ └── default/
│ ├── classes/
│ ├── lwc/
│ ├── aura/
│ └── ...
├── scripts/
├── sfdx-project.json
├── package.json
└── README.mdThe exact files vary by CLI version, so do not worry if your listing differs a little. These items matter most:
| Item | Purpose |
|---|---|
| `sfdx-project.json` | Project configuration. The CLI reads it to learn where your source lives. |
| `force-app/` | The default package directory. Your metadata source goes here. |
| `config/project-scratch-def.json` | A scratch org definition file. The scratch org chapter uses it. |
| `.forceignore` | Lists files the CLI skips when it deploys or retrieves. |
| `.gitignore` | Lists files Git skips. |
| `scripts/` | A place for helper scripts, such as anonymous Apex files. |
Read sfdx-project.json
This file marks a folder as a Salesforce DX project. The CLI looks for it in the current directory and in its parent directories. If it cannot find one, project commands that need it fail.
A generated file looks like this:
{
"packageDirectories": [
{
"path": "force-app",
"default": true
}
],
"name": "myproject",
"namespace": "",
"sfdcLoginUrl": "https://login.salesforce.com",
"sourceApiVersion": "62.0"
}Your sourceApiVersion will match the API version of your CLI release, so it can differ from the value above.
Key properties
packageDirectoriesis a list of folders that hold source. Each entry has apath. Exactly one entry should have"default": true. The CLI treats that folder as the place to put new source.nameis the project name.namespaceis empty unless you build a managed package that uses a namespace.sfdcLoginUrlis the login URL the CLI uses when you authorize an org. Change it if you work with a sandbox or a My Domain login page.sourceApiVersionis the Salesforce API version used when the CLI converts, deploys, and retrieves source. Changing it changes which metadata types and fields are available.
Multiple package directories
A project can have more than one source folder. This is common when you split a large codebase into modules.
{
"packageDirectories": [
{
"path": "force-app",
"default": true
},
{
"path": "shared-utils",
"default": false
}
],
"name": "myproject",
"namespace": "",
"sfdcLoginUrl": "https://login.salesforce.com",
"sourceApiVersion": "62.0"
}When you deploy without naming a folder, the CLI deploys every package directory in the file. When you pass --source-dir, it deploys only the path you give it.
The source format
Metadata in a DX project uses source format, not the older metadata API format. Source format splits some large metadata types into smaller files. For example, a custom object is a folder with one file per field, instead of one large XML file.
A custom object in source format looks like this:
force-app/main/default/objects/Invoice__c/
├── Invoice__c.object-meta.xml
├── fields/
│ └── Amount__c.field-meta.xml
└── listViews/
└── All.listView-meta.xmlSmaller files help in two ways. Two developers who change different fields rarely edit the same file, so merge conflicts are less common. Diffs in version control are also easier to read.
Each metadata file ends in -meta.xml. Apex classes are the exception in one respect: an Apex class has its code file and a companion metadata file.
force-app/main/default/classes/
├── HelloWorld.cls
└── HelloWorld.cls-meta.xmlIf you create a class by hand, you need both files. The companion file sets the API version and status. Generating the class with the CLI creates both for you, which avoids this error.
Add source with the CLI
You can generate common components with sf apex generate class. This example creates an Apex class in the default package folder.
sf apex generate class --name HelloWorld --output-dir force-app/main/default/classesThe command writes HelloWorld.cls and HelloWorld.cls-meta.xml. Open the first file and you will see an empty class:
public with sharing class HelloWorld {
public HelloWorld() {
}
}Other generators follow the same pattern, such as sf lightning generate component for Lightning web components. Use sf apex generate --help and sf lightning generate --help to see what is available.
Initialize version control
A DX project is meant to live in Git. The generated .gitignore already excludes local files such as the .sfdx and .sf folders, where the CLI stores cached data.
git init
git add .
git commit -m "Initial Salesforce DX project"Do not commit auth files or access tokens. The CLI stores org credentials in your user home directory, outside the project, so a normal commit does not include them. Keep it that way, and do not copy credentials into the project folder.
Use .forceignore
The .forceignore file works like .gitignore, but for deploy and retrieve. Any path that matches a pattern is skipped when the CLI deploys to an org or retrieves from one.
# Ignore all profiles in the project
**/profiles/**
# Ignore a single file
force-app/main/default/classes/DoNotDeploy.clsThe generated file already ignores a few things, such as the package.xml file and some Lightning web component tooling files. Edit it when you want to exclude metadata that you do not manage in source control.
How the CLI finds your project
Commands that deploy or retrieve source need to know which project you mean. They resolve it from your working directory.
The CLI starts in the current directory, looks for sfdx-project.json, and moves up one level at a time. This is why you can run sf project deploy start from force-app/main/default/classes and still have it work. It is also why running the same command from your home directory fails with an error that says the command is not inside a project.
Common errors
- The command says it is not in a project. You are outside a folder tree that contains
sfdx-project.json. Runpwdand change into the project. - A deploy finds nothing to deploy. The path you passed to
--source-diris not inside a package directory listed insfdx-project.json, or.forceignoreexcludes it. - An Apex class fails to deploy because the metadata file is missing. A
.clsfile needs its.cls-meta.xmlcompanion. Generate classes with the CLI. - Your metadata types are rejected. The
sourceApiVersionis older than the version that introduced the type. Raise the value. - The JSON file will not parse. A trailing comma or a missing quote in
sfdx-project.jsonbreaks every project command. Check it with a JSON validator.
Check your work
After you generate a project, confirm that the CLI recognizes it and sees your source. From the project root, list the folder and print the configuration.
ls
cat sfdx-project.jsonYou should see force-app in the listing and the JSON shown earlier in the file. In the next chapter you will deploy this source to your default target org and retrieve it back.
Exercise
You run sf project deploy start from your home directory and the CLI reports that you are not inside a project. What is the cause, and what is the fix?
Show answer
The CLI searches the current directory and its parents for sfdx-project.json and finds none. Change into the project folder (or any folder under it) and run the command again.
Exercise
Your sfdx-project.json lists two package directories, force-app and shared-utils. You run sf project deploy start --source-dir force-app. Which source is deployed, and what would deploy both?
Show answer
Only force-app is deployed, because --source-dir limits the deploy to the path you give. Running the command without --source-dir deploys all package directories in the file.
Exercise
You create HelloWorld.cls by hand in force-app/main/default/classes and the deploy fails. What file is likely missing, and how can you avoid the problem?
Show answer
The companion file HelloWorld.cls-meta.xml is missing. Generate the class with sf apex generate class, which writes both files.