user4349397
user4349397

Reputation: 39

Switch working MEAN project to angular universal

I have a working MEAN project. On client side i am using angular (not angularjs) and on server side i am using experss and mongodb.

I have read about angular universal lately, but i cant figure out what i am suppose to change and how the directory structure should be.

Can someone explain to me what the steps or give me a tutorial for this case?

Upvotes: 0

Views: 513

Answers (1)

k0hamed
k0hamed

Reputation: 502

You need to install platform-server and animations(required for the platform-server) package

npm i @angular/platform-server @angular/animations

Then edit your appModule to import

BrowserModule.withServerTransition({appId: 'Your-App'})

instead of BrowserModule. Then, create the server app module

// src/app/app.server.module.ts
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';

@NgModule({
imports: [
    ServerModule,
    AppModule
],
bootstrap: [AppComponent]
})
export class AppServerModule { }

after that you need to create a new express server in src/server.ts

import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server'
import { enableProdMode } from '@angular/core'
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory'
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';
import * as logger from 'morgan';
// API router 
import { router } from './api/router';

const PORT = 4000;

enableProdMode();

const app = express();

const template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
  const opts = { document: template, url: options.req.url };

  renderModuleFactory(AppServerModuleNgFactory, opts)
    .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src');
app.use(logger('dev'));

// Backend API 
app.use('/api', router);

app.get('*.*', express.static(join(__dirname, '..', 'dist')));

app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(PORT, () => {
  console.log(`listening on http://localhost:${PORT}!`);
});

Where router is the holder of your API it would be something like that

// src/api/router.ts
import {Router} from 'express';

export const router = Router(); 

router.get('/test', function (req, res) {
  const d = {
    data: 'Api works!'
  };
  res.send(d);
});

now exclude the server from src/tsconfig.app.json

"exclude": [
    "server.ts", // Add it 
    "test.ts",
    "**/*.spec.ts"
]
}

edit tsconfig.json and add

"angularCompilerOptions": {
    "genDir": "./dist/ngfactory",
    "entryModule": "./src/app/app.module#AppModule"
}  

finally install ts-node

npm i -D ts-node

and edit your package.json scripts

"prestart": "ng build --prod && ngc",
"start": "ts-node src/server.ts"

there should be nothing more need to change except if your app is interacting with the DOM using jQuery or document you need to use Angular APIs instead.

Upvotes: 2

Related Questions