Deploy Angular application to Google Cloud Storage (GCP) with GZip compression

Google Cloud Storage Bucket Setup

Let’s create a bucket to deploy our Angular application. We would like to make this bucket public. To do so, we will have to change the permissions.

  1. Click on “Permission” tab, and click on “Add”. In the modal box, enter allUsers in “New principals” and Storage Object Viewer in “Role”.
  2. Click on “Save”. This will make your bucket public. BE CAREFUL WHAT YOU UPLOAD IN THIS BUCKET. ANYONE CAN VIEW IT.

Build Angular app with — base-href

The important step while building an Angular application is to specify the --base-href. Because, once deployed, the GCP Bucket prefix name will be required to access the script, link and other resources. Let’s build an application with command as follows. Make sure you put the forward slash/ in front and back of bucket name.

Syntax: ng build -c production --base-href /<BUCKET_NAME>/For example: ng build -c production --base-href /ng-compression-demo/

Deploy Angular app to GCP Bucket using gsutil

There are many ways to upload Angular application to GCP Bucket. The simplest one is to manually upload files to the Bucket. And then apply Content-Encoding: gzip metadata to each object manually or via some script.

gsutil -m -o "GSUtil:parallel_process_count=1" cp -r -z js,css ./dist/ng-gzip-compression/* gs://ng-compression-demo
  1. -o "GSUtil:parallel_process_count=1 This command is required when there is a python version issue (which is always there, isn’t it?). This command disables multi threading settings for the tool.
  2. cp -r -z <file extensions to compress> <source_dir> <bucket_uri> Here, -r tell cp command to do recursive copy. -z tells cp command to compress all file types, e.g. -z js,css. The local files won’t be compressed, the tool will create a compressed file temporary and upload them to bucket. This flag also sets Content-Encoding: gzip metadata for provided file types while uploading. So, you don’t have to do it manually again.

Verification

We can verify the size reduction of files uploaded to GCP bucket. For example, the main.js from dist folder has 196Kb size.

GitHub Repository

I have updated the original GitHub repository for GCP demo. In package.json the file, you will find two commands gcp-build and gcp-deploy which encapsulate the big commands. You can simply run npm run gcp-build to build the application with your own bucket-name for --base-href value, and npm run gcp-deploy to deploy the output content into your bucket.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store