angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

Integrating angular2 Universal with angular CLI project

Open vinodbhargava opened this issue 10 years ago • 214 comments

  1. OS - Windows 8

  2. Versions - angular-cli: 1.0.0-beta.5 node: 4.3.1 os: win32 x64

  3. Yes, the app was created using CLI

  4. Steps - A. Created the app using following command - ng new testApp

    B. Installed angular2-universal dependencies as mentioned in -
    Angular 2 Universal quickstart

    C. Deployed client using command - ng server (server started on port 4200) Started express server through - node server.js (server started on port 3000)

    D. Accessed the client and got following message in browser - test-app works! But when accessing http://localhost:3000 it gives below error message in console -

EXCEPTION: Error: Protocol "d:" not supported. Expected "http:". STACKTRACE: Error: Protocol "d:" not supported. Expected "http:". at new ClientRequest (_http_client.js:52:11) at Object.exports.request (http.js:31:10) at Object.exports.get (http.js:35:21) at D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\angular2-universal\dist\node\platform\node_xhr_impl.js:53:22 at ZoneDelegate.invoke (D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\zone.js\dist\zone-node.js:281:29) at Object.NgZoneImpl.inner.inner.fork.onInvoke (D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\@angular\core\src\zone\ng_zone_impl.js:45:41) at ZoneDelegate.invoke (D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\zone.js\dist\zone-node.js:280:35) at Zone.run (D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\zone.js\dist\zone-node.js:174:44) at NgZoneImpl.runInner (D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\@angular\core\src\zone\ng_zone_impl.js:76:71) at NgZone.run (D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\@angular\core\src\zone\ng_zone.js:223:66) D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\@angular\core\src\application_ref.js:302 throw e; ^

Kindly suggest if i had missed any step.

Any help will be appeciated.

vinodbhargava avatar Jun 09 '16 08:06 vinodbhargava

I can confirm a similar behaviour:

$ node server-test.js 
/mypath/node_modules/@ng-bootstrap/ng-bootstrap/alert/alert.js:1
(function (exports, require, module, __filename, __dirname) { import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy, } from '@angular/core';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:533:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.28 (/mypath/dist-server/main.bcce3a638266c1136166.bundle.js:1:2933)

esistgut avatar Jul 27 '17 08:07 esistgut

@esistgut I guess we could open the issue in each repo, for instance i found this about ng-bootstrap

  • https://github.com/ng-bootstrap/ng-bootstrap/issues/1593#issuecomment-304612841

I think this is related to the build system, use webpack to make the transpile of your project

  • https://stackoverflow.com/questions/43692755/how-to-use-ngx-bootstrap-with-angular4-with-server-side-rendering

@antoineol this same solution kind of work on compile time for flex-layout as well, but when you run it thet grid-system/css does not work.. this was my experience using flex-layout in the angular-ssr project

mariohmol avatar Jul 27 '17 12:07 mariohmol

Noted, thanks. I'm just wondering if asking all libraries to update their bundle format for SSR is the right approach here. The webpack transpilation might be a bit better. Although flex-layout seems to still have something to fix anyway.

antoineol avatar Jul 27 '17 16:07 antoineol

Just checking out the 1.3 rc2 universal rendering capabilities. Is it expected that the dist-server build doesn't include any modules from @angular/* etc?

I can run the bundle as long as the modules required are available in node_modules, but it does not run without, as it looks for i.e. @angular/core.

Tried coding the main.server.ts to include:

import { AppServerModule } from './app/app.server.module';
import { renderModule } from '@angular/platform-server';
// Load zone.js for the server.
import 'zone.js/dist/zone-node';

// Load the index.html file.
const index = `
  <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>SsrAngular</title>
      <base href="/">
      <meta name="viewport" content="width=device-width,initial-scale=1">
      <link rel="icon" type="image/x-icon" href="favicon.ico">
      <link href="styles.d41d8cd98f00b204e980.bundle.css" rel="stylesheet"/>
    </head>
    <body>
      <app-root></app-root>
      <script type="text/javascript" src="inline.20497c77615e2913cbc9.bundle.js"></script>
      <script type="text/javascript" src="polyfills.1553fdd8173a081c720c.bundle.js"></script>
      <script type="text/javascript" src="vendor.fd573dc8ddf6ad07fe6a.bundle.js"></script>
      <script type="text/javascript" src="main.3dfa3440b0d6630d7495.bundle.js"></script>
    </body>
  </html>
`;

export const renderView = (callback, path, data, viewBag) => {
  renderModule(AppServerModule, { document: index, url: '/' })
    .then(html => callback(null, html));
};

I am new to universal angular, and was trying to run it with: https://github.com/pauldotknopf/JavaScriptViewEngine as we already have a React solution running with that one.

MartinSvarrer avatar Jul 27 '17 17:07 MartinSvarrer

import { Component, ElementRef, EventEmitter, forwardRef, Input, Output, ViewEncapsulation } from '@angular/core'; ^^^^^^ SyntaxError: Unexpected token import at createScript (vm.js:74:10) at Object.runInThisContext (vm.js:116:10) at Module._compile (module.js:533:28) at Object.Module._extensions..js (module.js:580:10)

same issue here with ngx-quill and ng-bootstrap, any workaround?

SebastianPodgajny avatar Jul 28 '17 01:07 SebastianPodgajny

has anyone tried to reproduce the steps in: https://github.com/angular/angular-cli/wiki/stories-universal-rendering

After running ng build --prod --app 1 it also produces a inline bundle:

chunk {0} styles.d41d8cd98f00b204e980.bundle.css (styles) 0 bytes {2} [initial] [rendered]
chunk {1} main.c86b031d2c0a09ba2c12.bundle.js (main) 346 bytes [initial] [rendered]
chunk {2} inline.d1514d289cf4dea70986.bundle.js (inline) 1.42 kB [entry] [rendered]

I created a js file at the project root server.js and added the "Testing the bundle" in there, but keep on getting this error: ReferenceError: webpackJsonp is not defined

I check the main bundle and it starts with webpackJsonp, which isn't defined. Anyone knows how to solve this ?

P.S. i'm running @angular/[email protected]

suau avatar Jul 28 '17 07:07 suau

@suau Sounds like you are running the client bundle js file. At least I get the same error when running the normal dist bundle with rc2.

MartinSvarrer avatar Jul 28 '17 07:07 MartinSvarrer

@MartinSvarrer Thanks big times, I've built it from scratch about 10 times and tried small changes, somehow I always forgot to add the "platform": "server" entry to the angular-cli.json. I was about to tell you that I have the bundles in two distinct folders (dist and dist-server) and couldn't possibly run the client bundle, but decided to double check for that key. Big thanks, you saved my sanity and the weekend.

suau avatar Jul 28 '17 08:07 suau

It seems like the styles and scripts from the angular-cli.json are not included in the ssr-html. Is that on purpose ? Considering these are meant for globally available styles and scripts that's unexpected.

What's the recommended way to do it ? Putting it in the src/assets folder and including it in the src/index.html does work, but then I'll need to run a separate gulp/webpack to minify it.

P.S. the component CSS is properly inlined.

suau avatar Jul 28 '17 14:07 suau

I currently have the following problem:

ERROR TypeError: this.html.charCodeAt is not a function
    at module.exports.Preprocessor.advance (/myapp/node_modules/parse5/lib/tokenizer/preprocessor.js:124:24)
    at module.exports.Tokenizer._consume (/myapp/node_modules/parse5/lib/tokenizer/index.js:278:30)
    at module.exports.Tokenizer.getNextToken (/myapp/node_modules/parse5/lib/tokenizer/index.js:236:23)
    at module.exports.Parser._runParsingLoop (/myapp/node_modules/parse5/lib/parser/index.js:393:36)
    at module.exports.Parser.parseFragment (/myapp/node_modules/parse5/lib/parser/index.js:348:10)
    at Object.parseFragment (/myapp/node_modules/parse5/lib/index.js:23:19)
    at Parse5DomAdapter.setInnerHTML (/myapp/node_modules/@angular/platform-server/bundles/platform-server.umd.js:947:49)
    at Parse5DomAdapter.setProperty (/myapp/node_modules/@angular/platform-server/bundles/platform-server.umd.js:583:18)
    at EmulatedEncapsulationServerRenderer2.DefaultServerRenderer2.setProperty (/myapp/node_modules/@angular/platform-server/bundles/platform-server.umd.js:2106:44)
    at BaseAnimationRenderer.setProperty (/myapp/node_modules/@angular/platform-browser/bundles/platform-browser-animations.umd.js:505:27)

Note 1: as the problem seems to be related to animations I tried to

  1. Use NoopAnimationsModule on the server module and BrowserAnimationsModule in the browser module
  2. To completly remove animations from my project and
  3. To completly remove animations from my project but still load NoopAnimationsModule from the server module.

Note 2: I do an additional compilation step using webpack to whitelist ngrx and ng-bootstrap this is my webpack.config.js:

const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  entry: {
    server: './server.ts'
  },
  resolve: {
    extensions: ['.ts', '.js']
  },
  target: 'node',
  externals: [nodeExternals({
    whitelist: [
      /^@ng-bootstrap\/ng-bootstrap/,
      /^@ngrx/,
    ]
  })],
  node: {
    __dirname: true
  },
  output: {
    path: path.join(__dirname, 'dist-server'),
    filename: '[name]-webpack.js'
  },
  module: {
    rules: [
      { test: /\.ts$/, loader: 'ts-loader' }
    ]
  }
};

This is my server.ts:

import * as express from 'express';
import {ValueProvider} from '@angular/core';
import {renderModuleFactory} from '@angular/platform-server';
import {join} from 'path';
import {readFileSync} from 'fs';

import * as xhr2 from 'xhr2';
xhr2.prototype._restrictedHeaders.origin = false;

// Load zone.js for the server.
require('zone.js/dist/zone-node');
require('reflect-metadata');
const AppServerModuleNgFactory = require('./dist-server/main.b02d144863c57aa83124.bundle').AppServerModuleNgFactory;


const template = readFileSync('./src/index.server.html', { encoding: 'utf8' });

// Render to HTML and log it to the console.
// renderModuleFactory(AppServerModuleNgFactory, {document: index, url: '/'}).then(html => console.log(html));

const app = express();

app.engine('html', (_, options, callback) => {
  const opts = {
    document: template, url: options.req.url, extraProviders: [
      <ValueProvider>{
        provide: 'REQUEST',
        useValue: options.req,
      }]
  };

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

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

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

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

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

esistgut avatar Jul 29 '17 09:07 esistgut

Universal seems to be working pretty well now in 1.3. Any idea on when lazy loading will be supported though?

dottodot avatar Aug 11 '17 07:08 dottodot

how to solve ng-bootstrap issue?

node_modules/@ng-bootstrap/ng-bootstrap/typeahead/typeahead.js:1 (function (exports, require, module, __filename, __dirname) { import { ComponentFactoryResolver, Directive, ElementRef, EventEmitter, forwardRef, Injector, Input, NgZone, Output, Renderer2, ViewContainerRef } from '@angular/core'; ^^^^^^ SyntaxError: Unexpected token import at Object.exports.runInThisContext (vm.js:73:16) at Module._compile (module.js:543:28)

dimitriy-k avatar Aug 11 '17 12:08 dimitriy-k

@dimitriy-k add an additional compilation step using webpack to whitelist it, something like this:

const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  entry: {
    server: path.join(__dirname, 'your_universal_loader.ts'),
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
  target: 'node',
  externals: [nodeExternals({
    whitelist: [
      /^@ng-bootstrap\/ng-bootstrap/,
    ]
  })],
  node: {
    __dirname: false,
  },
  output: {
    path: path.resolve(__dirname,  'dist-server'),
    filename: '[name]-webpack.js',
  },
  module: {
    rules: [
      { test: /\.ts$/, loader: 'ts-loader'}
    ]
  }
};

esistgut avatar Aug 11 '17 12:08 esistgut

@suau https://github.com/angular/angular-cli/issues/1050#issuecomment-318672196:

It seems like the styles and scripts from the angular-cli.json are not included in the ssr-html. Is that on purpose ? Considering these are meant for globally available styles and scripts that's unexpected. ...

I'm experiencing the same problem and am confused. Is this an indication that server/browser Transitioning is not happening or it is broken?

Does anyone have a basic example/starter repo showing how to set up angular-cli v1.3+ so that global browser scripts/styles are included in the server rendered output?

somombo avatar Aug 12 '17 01:08 somombo

Do you have any updates about support lazy loading?

PSTime avatar Aug 15 '17 10:08 PSTime

@PSTime you may find this useful https://github.com/angular/universal/tree/master/modules/ng-module-map-ngfactory-loader

somombo avatar Aug 15 '17 18:08 somombo

https://github.com/angular/universal/tree/master/modules/ng-module-map-ngfactory-loader does seem to work thanks

dottodot avatar Aug 16 '17 10:08 dottodot

Thank you @somombo, it useful for me. But angular cli doesn`t generate LAZY_MODULE_MAP (I have added platform=server), do you have any suggestion ?

PSTime avatar Aug 17 '17 05:08 PSTime

@PSTime I haven't tested it yet.. but perhaps @FrozenPandaz or @intellix may be able to provide some guidance. Ref #6913 #7107

somombo avatar Aug 17 '17 06:08 somombo

Hi Guys. I have a project that created with angular/cli(https://github.com/angular/angular-cli) and I am trying to set up Universal in my app. so I followed https://github.com/angular/angular-cli/wiki/stories-universal-rendering but it doesn't work for me.

BearandYoon avatar Aug 21 '17 15:08 BearandYoon