How to add and install dependencies?
Problem to Solve?
When creating schematics, you may encounter the need to install dependencies.
What does installing dependencies entail?
- Modifying the
package.json
file to include the new dependencies. Dependencies can be of various types:dev
,default
,peer
,optional
. - Installing these dependencies based on the package.json file.
Solution
There are two main approaches to solving this problem:
- If you know the specific version of the library you want to install, you can directly modify the
package.json
and then run a task to install the dependencies. - If you need to install the latest version but are unsure of its version number, you can call a
Node
method.
All the files and methods mentioned in this tutorial can be found in your schematic project under the /utils
folder.
It is recommended to specify the version of the library when adding dependencies to your project. This approach ensures you are aware of the required settings for that version. Installing the latest version might introduce breaking changes that could affect your schematic code.
Adding Dependencies to the Package.json and Installing Them
The Angular Schematic repository provides useful utilities for this purpose.
Installing Dependencies with Node Commands
Node Methods vs NodePackageInstallTask
We’ve explored two solutions. The first uses @angular-devkit
’s native options, requiring more code. The second leverages Node.js’s spawnAsync
, a native method.
The drawback of the second solution is its operation outside the staging area
. This area allows the Tree
object to roll back changes if any issues occur during modification of the package.json
or any file. Additionally, the first solution supports dry-run
mode, simulating actions without executing them. Thus, if you opt for the second solution, you’ll need to implement dry-run
functionality manually.