Continous Integration (CI) and Continuous Deployment (CD) are essential practices for a production-ready Node.js application written in TypeScript. With GitHub Actions, setting up CI/CD is streamlined, allowing code to be seamlessly tested and deployed. This guide will step through how to create a workflow using GitHub Actions to build, test, and deploy a Node.js application written in TypeScript.
Creating Your Node.js Application
Before adding CI/CD, you need to have a Node.js application written in TypeScript. Initialize a new Node.js project with TypeScript:
npx tsc --init
npm init -y
Add your application code to this setup according to your project’s requirements.
Configuring TypeScript
Ensure TypeScript is set up to compile code to a directory that can be targeted by the CI/CD pipeline, such as build
:
{
...
"compilerOptions": {
"outDir": "./build",
}
...
}
Setting Up CI/CD with GitHub Actions
Create a new file in your repository named .github/workflows/nodejs.yml
. The file structure automatically assigns it as a GitHub Action. Below is a simplified CI/CD workflow:
name: Node.js CI/CD
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14.x, 16.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: npm install, build, and test
run: |
npm install
npm run build --if-present
npm test
This YAML configures a GitHub Actions workflow that triggers on push or pull request events to the main branch. It then sets up a job to build the project using different versions of Node.js.
Implementing Deployment
Let’s extend the workflow to include deployment. This can be done by adding an additional step at the end of the build job or by creating a new job that depends on the build job. Here’s how you might conditionally deploy when pushing to `main`:
(
- name: Deploy
if: github.ref == 'refs/heads/main'
run: echo "Deploying to production!" // Replace this with your actual deployment command
)
Testing and Troubleshooting
Once you push the workflow file to your repository, any push to the relevant branches triggers the action. Review the actions tab on your GitHub repository to see the results of the workflow, troubleshoot any failures, and validate that it works as expected.
Conclusion
A proper CI/CD setup with GitHub Actions ensures your application is always ready for production with the least manual intervention. This introduction only scratches the surface, and real-world applications may require more sophisticated configurations dependent on specific needs.