AngularJS app on AWS S3

  • by
AngularJS on S3

You have developed your own web application using AngularJS with backend built on NodeJS, Java or any other technology of choice. In your local, you run it by just running npm start or ng serve. But when it comes to running it on a production environment, you either have to choose a hosting which lets you run NodeJS apps or any cloud service. You can use Heroku, AWS EC2, Azure, GCP or any other numerous services which give you this functionality. But the catch is, they cost more and if you are on a budget and have built a small web application, say like a dashboard just to enter data, this hurts.

So, in this article, we are going to address the way how we can just deploy the application to AWS S3 (other environments coming soon) which costs significantly less than any computing environment. The trick is to build the app, get the bundle and deploy the bundle on an environment. This way it behaves a simple web application with javascript. In this case, I will be using webpack.

Prerequisites

  • Already developed application in AngularJS
  • An AWS account
  • Code repository in GitLab for continuous integration (optional). You can use other repositories and configure it likewise

Preparing AWS S3

  • Navigate to S3 Console and create a bucket. Name the bucket after your domain name. For example if your domain name is deepakdhamuria.com, then name it deepakdhamuria.com.
  • Click next and under Set permissions and deselect”Block all public access” and create the bucket
  • Open the bucket, navigate to properties and click on Static website hosting. Under that select “Use this bucket to host a website”. Click save and now your bucket is ready.

Preparing CloudFront for routing

  • Login to CloudFront Console and create a new Web Distribution.
  • In Origin Domain Name, select the S3 bucket you created above.
  • Select index.html for the Default Root Object and click save

Preparing your code

  • Modify your package.json file to add scripts for build
"scripts": {
    "build": "webpack -p --progress --colors",
    -----other scripts-----
  },
  • Add a webpack.config.js file to the root of your repo. Below is an example. In this article, I am not going to dig deep inside how webpack works and it’s different options.
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  entry: {
    'app': './app/main.ts'
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: '[name].js',
    publicPath: '/'
  },
  resolve: {
    extensions: ['.ts', '.js', '.json', '.css', '.scss']
  },
  module: {
    exprContextCritical: false,
    rules: [
      {test: /\.ts$/, exclude: [/\.(spec|e2e)\.ts$/], use: ['awesome-typescript-loader', 'angular2-template-loader']},
      {test: /\.(html|css)$/, loader: 'raw-loader', exclude: /\.async\.(html|css)$/},
      {test: /\.async\.(html|css)$/, loaders: ['file?name=[name].[hash].[ext]', 'extract']},
      {test: /\.scss$/, exclude: /node_modules/, use: ['raw-loader', 'sass-loader']},
      {test: /\.png$/, exclude: /node_modules/, use: ['file'] },
      {test: /\.js$/, exclude: /node_modules/, loader: 'raw-loader'}
      // {test: /\.(woff|woff2|eot|ttf|svg)$/, exclude: /node_modules/, loader: 'url-loader?limit=1024&name=fonts/[name].[ext]'}
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./app/index.html"
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: ['app']
    }),
     new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    }),
    new CopyWebpackPlugin([
        { from: "app/assets" }
    ]),
  ],
  devServer: {
    historyApiFallback: true,
    stats: "minimal",
    inline: true
  }
};

Now just run npm run build and the code builds. After it succeeds, upload the files from “dist” folder into the bucket/folder you created earlier and your site should be up and running.

BONUS – Deploy using GitLab CI or similar

  • Open your AWS acocunt and go to IAM under My Security Credentials. In there, create a new Access Key. Give access to the S3 bucket you created before. After creation save the access key ID and access key secret.
  • Under GitLab repo settings, go to CI/CD and under variables add two variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY and paste the values you fetched from AWS in previous step.
  • Create a .gitlab-ci.yml under your repo and paste following:
# This file is a template, and might need editing before it works on your project.
# Full project: https://gitlab.com/pages/plain-html
stages:
  - build
  - deploy

variables:
  AWS_DEFAULT_REGION: us-east-2
  BUCKET_NAME: deepakdhamuria.com

cache:
  paths:
    - vendor

buildApp:
  image: node:10.15.0-stretch
  stage: build
  script:
    - npm install
    - npm run build
  artifacts:
    paths:
      - dist/
    expire_in: 1 hour

deploys3:
  image: python:latest
  stage: deploy
  dependencies:
    - buildApp
  before_script:
    - pip install awscli
  script:
    - aws s3 sync ./dist s3://${BUCKET_NAME}

Now, when you check in any changes, this file will build and deploy your code onto the S3 bucket you have specified.

That’s it! This concludes the topic on how to deploy an AngularJS site in S3. Hope you liked the article.

Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.