NodeJs Deploy Script for Small Projects with Yarn Workspaces
March 10, 2023โข1,484 words
In preparation for my finals project, to have the implementation go more smoothly, I created an old-school Node.js script for uploading the applications to my test/demo server, which is an Ubuntu VPS running Caddy that handles the access to either the API or the Angular app (serving the files). Both are placed into directories inside /var/www/
The script can be run with yarn deploy [app | api]
which reads the dist directory of the selected workspace from its package.json, then packages the code and uploads it to the server. If api is selected, it will also install dependencies and reload the application (using PM2).
Yes, PM2 already offers a script which achieves a similar result, but it cant' be set to copy a specific directory as it pulls the whole code from a remote repo. Hence I needed something else for my monorepo. Additionally I wanted to upload the code directly from the local machine and more control of what is happening.
Usage
- Make sure the remote can be connected to, usually with an SSH config entry
- Create a .env in the root of the project with the following variables:
REMOTE_ADDRESS
- server where the app will be deployed
REMOTE_USER
- user on the server which will execute the process, should have sufficient permissions
APP_REMOTE_DIRECTORY
- where the app should be placed on the server, e.g. /var/www/app
API_REMOTE_DIRECTORY
- where the api should be placed on the server
- Specify a
distDirectory
in the package.json of each workspace - Install dotenv and tar
yarn add -D dotenv tar
- Create the deployer.js in the root of the project:
- Add as script to the root package.json
- Run with
yarn deploy [workspace]
Enjoy!