How to deploy Angular 9 universal app with firebas

2020-06-18 03:41发布

问题:

I recently update to latest angular version 9 and created a app . I made this app universal using the command : ng add @nguniversal/express-engine and then i build the app using : npm run build:ssr && npm run serve:ssr

now dist folder is created with browser and server folder in it but no server.js file was created in dist root directory and also webpack config file was not created when i build the app with angular 9. Please tell me a way on how can i deploy my new app build on angular 9 universal to firebase cloud functions and hosting

回答1:

as of angular 9 you will have the following build structure

 dist            
  ├── server            
  |    └── main.js and some other files like firebase analytics stuff       
  └── browser                
       └── index.html and all files for the broswer 

now in order to test this you need to give the following command from your project root dir

node dist/server

this ll invoke the main.js file in the server folder and you app ll be served locally. info ll be printed on the screen about the localhost url with port.

now in order to deploy to firebase use the following code

import * as functions from 'firebase-functions';
import * as path from 'path';

const app = require(path.resolve(__dirname, "./dist/server/main")).app; // change the path according to your project structure
const myApp = functions.https.onRequest(app());

and you ll have a function myApp where you can access your Angular SSR App

[UPDATE]

there is no fixed place where you initialise your functions. all that matters is that the path of dist/server/main is corrent in myApp function

one more thing i forgot to mention is that you have to update your package.json hosting field to the following configuration =>

  ...
  "hosting": [{
        "target": "app",
        "public": "/dist/browser", // change it according to your directory structure
        "rewrites": [{
            "source": "**",
            "function": "myApp"
        }]
  }]
  ...

hope it helps ;)