Coder Social home page Coder Social logo

stanleyeosakul / angular-universal-firebase Goto Github PK

View Code? Open in Web Editor NEW
14.0 1.0 1.0 187 KB

Angular Universal app using Firebase Cloud Functions

License: MIT License

TypeScript 63.77% JavaScript 22.01% HTML 13.47% CSS 0.74%
angular firebase firebase-functions angular-universal

angular-universal-firebase's Introduction

Deploy Angular Universal App with Firebase

This step-by-step tutorial will show you how to deploy a Angular App with server-side rendering using Angular Universal with Firebase Hosting. This project was generated with Angular CLI version 1.7.1.

  • Angular version: 5.2.6
  • Firebase CLI version: 3.17.4

Generate a Universal Angular App

Angular CLI has native Universal support starting from v1.6. We will use the CLI to quickly generate Angular Universal server files, and then make some minor changes for our production build.

  1. Create a new Angular project

    ng new angular-universal-firebase
    
  2. Generate Angular Universal using Angular CLI (v1.6 or greater)

    ng generate universal universal
    
  3. Install @angular/platform-server

    yarn add @angular/platform-server
    
  4. Modify main.server.ts to the following:

    import { enableProdMode } from '@angular/core';
    export { AppServerModule } from './app/app.server.module';
    
    enableProdMode();
  5. Add /dist-server to .gitignore

    # compiled output
    /dist
    /dist-server
    ...
    
  6. Build the app (/dist folder) and the server to render the app (/dist-server folder).

    ng build --prod && ng build --prod --app universal --output-hashing=none
    

Deploying to Firebase

Since we now have an Angular app with a /dist and /dist-server directories, we will now use Firebase Cloud Functions to serve our application. This guide was originally written by Aaron Te and can be found at Hackernoon: Deploy Angular Universal w/ Firebase, but has been slightly modified with minor changes.

  1. Create a Firebase project (eg. angular-universal-firebase)

  2. Log in to firebase using

    firebase login
    
  3. Initialize Firebase in the Angular project

    firebase init
    
    • Select Functions and Hosting for features
    • Select the firebase project you created (eg. angular-universal-firebase)
    • Select javascipt as the language used to write Cloud Functions
    • Select no to install dependencies with npm
    • Select all defaults for Hosting
  4. Add Angular dependencies to functions/package.json, including @angular, rxjs, and zone.js. The easiest way to add these dependencies will be to copy them from your root package.json file. IMPORTANT: Install dependencies in the functions directory with yarn. NPM does not properly install firebase-admin. You will have to install express using yarn add express.

    "dependencies": {
      "@angular/animations": "^5.2.6",
      "@angular/common": "^5.2.6",
      "@angular/compiler": "^5.2.6",
      "@angular/core": "^5.2.6",
      "@angular/forms": "^5.2.6",
      "@angular/http": "^5.2.6",
      "@angular/platform-browser": "^5.2.6",
      "@angular/platform-browser-dynamic": "^5.2.6",
      "@angular/platform-server": "^5.2.6",
      "@angular/router": "^5.2.6",
      "express": "^4.16.2",
      "firebase-admin": "~5.9.0",
      "firebase-functions": "^0.8.1",
      "rxjs": "^5.5.6",
      "zone.js": "^0.8.20"
    },
  5. Install all dependencies in the functions directory using yarn.

    yarn install
    
  6. Copy the dist and dist-server folders into the functions directory. This is because Firebase functions cannot access files outside of this directory. There should now be exact copies of those two folders in functions/dist and functions/dist-server, respectively.

  7. Create Firebase function (index.js) to serve the app. This file is found in the functions directory.

    require('zone.js/dist/zone-node');
    
    const functions = require('firebase-functions');
    const express = require('express');
    const path = require('path');
    
    const { enableProdMode } = require('@angular/core');
    const { renderModuleFactory } = require('@angular/platform-server');
    const { AppServerModuleNgFactory } = require('./dist-server/main.bundle');
    
    enableProdMode();
    
    const index = require('fs')
        .readFileSync(path.resolve(__dirname, './dist/index.html'), 'utf8')
        .toString();
    
    let app = express();
    
    app.get('**', function (req, res) {
        renderModuleFactory(AppServerModuleNgFactory, {
            url: req.path,
            document: index
        }).then(html => res.status(200).send(html));
    });
    
    exports.ssr = functions.https.onRequest(app);
  8. Update firebase.json to:

    {
        "hosting": {
            "public": "dist",
            "ignore": [
                "firebase.json",
                "**/.*",
                "**/node_modules/**"
            ],
            "rewrites": [{
                "source": "**",
                "function": "ssr"
            }]
        }
    }
  9. Delete the /public folder that was automatically generated by Firebase functions during the firebase init process

    rm -rf public
    
  10. Delete dist/index.html from the root directory. This is so Firebase won’t serve the html file but rather run the ssr function.

  11. Add functions/dist, functions/dist-server and functions/node_modules to .gitignore

    # compiled output
    /dist
    /dist-server
    /functions/dist
    /functions/dist-server
    ...
    
    # dependencies
    /node_modules
    /functions/node_modules
    
  12. Deploy to Firebase

    firebase deploy
    

Further help

To get more help on the Angular CLI use ng help or go check out the Angular CLI README.

angular-universal-firebase's People

Contributors

angular-cli avatar stanleyeosakul avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

redcapua

angular-universal-firebase's Issues

Thanks

Thank you for this repo. The Youtube video David East did showing how to do SSR with Firebase hosting is a gimmick! This tutorial actually works.

In the video by the Google Developer Advocate, there is no repo with a working solution nor does he prove that it works on video. I spent 3 or 4 evenings after work trying to get it working. After coming across this tutorial I realized that the video could not have worked and is nothing more than a hoax.

Thank you.

The solution is not working with apps using HammerJS

Hi Stanley!
I can't use this method to deploy A5 apps to Firebase with SSR because my app is using the HammerJS lib and Angular Material.
The following error occurs during deployment if I use HammerJS:

Error: Error occurred while parsing your function triggers.
ReferenceError: window is not defined
at Object. (/private/var/folders/7c/78msd3tj5zj75g1_pbnmpf7m0000gn/T/fbfn_7305dKGJirWMAoKm/node_modules/hammerjs/hammer.js:2643:4)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
at Object.LYNW (/private/var/folders/7c/78msd3tj5zj75g1_pbnmpf7m0000gn/T/fbfn_7305dKGJirWMAoKm/dist-server/main.bundle.js:1:40603)
at l (/private/var/folders/7c/78msd3tj5zj75g1_pbnmpf7m0000gn/T/fbfn_7305dKGJirWMAoKm/dist-server/main.bundle.js:1:220)

Have you got any solution for this?

Kind rgds,
Barna

ReferenceError: html is not defined

Hi,
When i remove root dist/index.html this error show me when run the app

ReferenceError: html is not defined at E:\NodeJs Projects\Mangaka3rb - sarhansoft website\angular-universal-firebase\functions\index.js:25:30 at Layer.handle [as handle_request] (E:\NodeJs Projects\Mangaka3rb - sarhansoft website\angular-universal-firebase\functions\node_modules\express\lib\router\layer.js:95:5) at next (E:\NodeJs Projects\Mangaka3rb - sarhansoft website\angular-universal-firebase\functions\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (E:\NodeJs Projects\Mangaka3rb - sarhansoft website\angular-universal-firebase\functions\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (E:\NodeJs Projects\Mangaka3rb - sarhansoft website\angular-universal-firebase\functions\node_modules\express\lib\router\layer.js:95:5) at E:\NodeJs Projects\Mangaka3rb - sarhansoft website\angular-universal-firebase\functions\node_modules\express\lib\router\index.js:281:22 at param (E:\NodeJs Projects\Mangaka3rb - sarhansoft website\angular-universal-firebase\functions\node_modules\express\lib\router\index.js:354:14) at param (E:\NodeJs Projects\Mangaka3rb - sarhansoft website\angular-universal-firebase\functions\node_modules\express\lib\router\index.js:365:14) at param (E:\NodeJs Projects\Mangaka3rb - sarhansoft website\angular-universal-firebase\functions\node_modules\express\lib\router\index.js:365:14) at Function.process_params (E:\NodeJs Projects\Mangaka3rb - sarhansoft website\angular-universal-firebase\functions\node_modules\express\lib\router\index.js:410:3)

when i keep dist/index.html it not view never, but when try to open another page (url) directly it show to me again. like (myapp.com/login)

Followed the docs but I got the below error

/angular-universal-firebase/functions/index.js:12
const functions = require('firebase-functions');
^
SyntaxError: Identifier 'functions' has already been declared
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:545:28)
at Object.Module._extensions..js (module.js:582:10)
at Module.load (module.js:490:32)
at tryModuleLoad (module.js:449:12)
at Function.Module._load (module.js:441:3)
at Module.require (module.js:500:17)
at require (internal/module.js:20:19)
at /usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:18:11
at Object. (/usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:38:3)

Lazy loading

Hello, this method allows for lazy loaded modules to work? and prerenders them?

SSR Not Working

Hi,

image

The app not working on firebase, you can see the html content.

Any idea?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.