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.
You wouldn't need to start the Client separately, if you're using Universal it'll be serving everything through the server only. You want to access port 3000 then. Express is serving the index (w/ the universal app). Give that a shot and let me know
Hi @MarkPieszak, thanks for reverting.
I started the application on port 3000 only as suggested and then accessed the URL, but getting the same error again. I am attaching the screenshot for reference.
Try upgrading Node to 6+ or something, this might be some Express issue. It thinks you're trying to do d://something
instead of http://
etc. I think because of your hard-drive directory, bizarre.
You have:
provide(ORIGIN_URL, {useValue: 'http://localhost:3000'}), // <-- localhost3000 in there?
Thanks for the inputs @MarkPieszak, I will try it after upgrading Node to latest version.
Yes, i am having this line in my server.ts file -
provide(ORIGIN_URL, {useValue: 'http://localhost:3000'}),
The Express version that i am referring to is - "express": "^4.13.4"
@MarkPieszak, i had updated the node version to 6.2.1, however i am still getting the same error :(
Version update
Error message-
Please suggest if i am doing something wrong here.
Yeah, the same error happening when you generate app via angular-cli and add server code from https://universal.angular.io/quickstart/
Hi @neilhem, any luck?
no luck, on gitter chat of angular-universal I have written about error, so they told me that they will update code example as soon as possible
@gdi2290 Not sure if this one was on your radar, can't tell if it's CLI or Universal itself
I followed the example as well, but i have totally different errors coming from the server.ts file:
D:/Workspace/bitbucket/stock-front/tmp/broccoli_type_script_compiler-input_base_path-aCaBCBu3.tmp/0/src/server.ts (1, 23): Cannot find module 'path'.
D:/Workspace/bitbucket/stock-front/tmp/broccoli_type_script_compiler-input_base_path-aCaBCBu3.tmp/0/src/server.ts (2, 26): Cannot find module 'express'.
D:/Workspace/bitbucket/stock-front/tmp/broccoli_type_script_compiler-input_base_path-aCaBCBu3.tmp/0/src/server.ts (3, 29): Cannot find module 'body-parser'.
D:/Workspace/bitbucket/stock-front/tmp/broccoli_type_script_compiler-input_base_path-aCaBCBu3.tmp/0/src/server.ts (23, 37): Cannot find name '__dirname'.
D:/Workspace/bitbucket/stock-front/tmp/broccoli_type_script_compiler-input_base_path-aCaBCBu3.tmp/0/src/server.ts (29, 18): Cannot find name '__dirname'.
Did you guys had similar problems?
BR
Nevermind, got the same error as well.
EXCEPTION: Error: Protocol "d:" not supported. Expected "http:"
Yeah, the problem was that the typings command failed so I had to add the
ambientDependencies manually.
But I still get your error.
BR
On 11 June 2016 at 20:45, Vinod Bhargava [email protected] wrote:
@vaskgjuri https://github.com/vaskgjuri for fixing these errors -
- install the typings as mentioned in angular2-universal IO
https://universal.angular.io/quickstart/- add the reference to the typings in the server.ts file
Above errors should be gone.
Please try these steps and update.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/angular/angular-cli/issues/1050#issuecomment-225383345,
or mute the thread
https://github.com/notifications/unsubscribe/AGGmXFsw2_ntdRcs3ZLuYDA0uI-Siexpks5qKwJQgaJpZM4Ixuiz
.
Med vänlig hälsning | Met vriendelijke groet | Топли поздрави | Kind Regards
Vasko Gjurovski
Tel +38976361002
Bagdatska 15/7 | 1000 Skopje | Macedonia
www.polarcape.com
Polar Cape is representing Sweden in the European Business Awards
Please watch our video and vote http://www.businessawardseurope.com/ for
us if you think we should become National Public Champions
http://www.businessawardseurope.com/
http://www.greatplacetowork.se/baesta-arbetsplatser
Polar Cape is one of the best places to work 2015
I did a little more research and I tried to follow this example:
http://mean.expert/2016/06/04/angular-2-loopback-universal/
However, at the end I got the same error message:
Error: Protocol "d:" not supported. Expected "http:"
This is making me think that this might be a problem with a newer version of one of the dependencies, but I just cannot pinpoint which one. Main suspects preboot and angular2-universal.
Still looking...
BR
I'll take a deeper look tomorrow and see if I have any luck integrating the CLI with it. Have you tried the Universal Starter? Also, Universal only works with router-deprecated at this moment, maybe it has something to do with that.
I did try the Universal starter and it was working fine, but as the CLI is
the recommended way of "managing" your app, it was only logical that we use
the CLI with Universal. And, no, I did not know that Universal works with
router-deprecated at the moment, which would be a huge drawback, as now it
is 2 versions behind (with the announcement of the 3.0 Router).
And, thanks for the help... :)
BR
On 11 June 2016 at 23:55, Mark Pieszak [email protected] wrote:
I'll take a deeper look tomorrow and see if I have any luck integrating
the CLI with it. Have you tried the Universal Starter? Also, Universal only
works with router-deprecated at this moment, maybe it has something to do
with that.—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/angular/angular-cli/issues/1050#issuecomment-225396651,
or mute the thread
https://github.com/notifications/unsubscribe/AGGmXLxwV9new6GzBlbhU9_37Ui9QQCjks5qKy7jgaJpZM4Ixuiz
.
Med vänlig hälsning | Met vriendelijke groet | Топли поздрави | Kind Regards
Vasko Gjurovski
Tel +38976361002
Bagdatska 15/7 | 1000 Skopje | Macedonia
www.polarcape.com
Polar Cape is representing Sweden in the European Business Awards
Please watch our video and vote http://www.businessawardseurope.com/ for
us if you think we should become National Public Champions
http://www.businessawardseurope.com/
http://www.greatplacetowork.se/baesta-arbetsplatser
Polar Cape is one of the best places to work 2015
FYI, I did try a stripped version of my app with the router-deprecated and
it still gives the same error:
EXCEPTION: Error: Protocol "d:" not supported. Expected "http:"
So I do not think it is the router that makes the problem.
BR
On 12 June 2016 at 03:18, Vasko Gjurovski vasko.[email protected]
wrote:
I did try the Universal starter and it was working fine, but as the CLI is
the recommended way of "managing" your app, it was only logical that we use
the CLI with Universal. And, no, I did not know that Universal works with
router-deprecated at the moment, which would be a huge drawback, as now it
is 2 versions behind (with the announcement of the 3.0 Router).And, thanks for the help... :)
BR
On 11 June 2016 at 23:55, Mark Pieszak [email protected] wrote:
I'll take a deeper look tomorrow and see if I have any luck integrating
the CLI with it. Have you tried the Universal Starter? Also, Universal only
works with router-deprecated at this moment, maybe it has something to do
with that.—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/angular/angular-cli/issues/1050#issuecomment-225396651,
or mute the thread
https://github.com/notifications/unsubscribe/AGGmXLxwV9new6GzBlbhU9_37Ui9QQCjks5qKy7jgaJpZM4Ixuiz
.
Med vänlig hälsning | Met vriendelijke groet | Топли поздрави | Kind
RegardsVasko Gjurovski
Tel +38976361002
Bagdatska 15/7 | 1000 Skopje | Macedonia
www.polarcape.com
Polar Cape is representing Sweden in the European Business Awards
Please watch our video and vote http://www.businessawardseurope.com/ for
us if you think we should become National Public Championshttp://www.businessawardseurope.com/
http://www.greatplacetowork.se/baesta-arbetsplatserPolar Cape is one of the best places to work 2015
Med vänlig hälsning | Met vriendelijke groet | Топли поздрави | Kind Regards
Vasko Gjurovski
Tel +38976361002
Bagdatska 15/7 | 1000 Skopje | Macedonia
www.polarcape.com
Polar Cape is representing Sweden in the European Business Awards
Please watch our video and vote http://www.businessawardseurope.com/ for
us if you think we should become National Public Champions
http://www.businessawardseurope.com/
http://www.greatplacetowork.se/baesta-arbetsplatser
Polar Cape is one of the best places to work 2015
Ok I'll take a look, yeah we haven't upgraded it yet mainly because of the ever changing router states, of course for the newest one we will update it as quickly as we can!
shouldn't angular CLI support universal from ground up?
e.g. ng generate universal node/asp.net
Unfortunately I don't think it could from the way it is now, because asp.net for example has an extremely different setup than a typical ng2 project.
It would have to be an add-on to the CLI if they had it, since it would be very different itself.
Steve Sanderson made a nice yeoman generator for asp.net core and angular2 (it's using Universal as well) if you want to take a look at it. http://blog.stevensanderson.com/2016/05/02/angular2-react-knockout-apps-on-aspnet-core/
thanks for the link. Is it possible/usable to combine this with angular CLI?
I haven't tried, but I think you have to of first made an app with ng new
to utilize the CLI :(
I would hope sometime in the future we can integrate a .NET add on for the CLI though
I believe @Brocco was looking into Universal integration, but I don't know more than that.
We are in the exploratory stages of integrating angular universal into the CLI to determine feasibility. Once that has been determined we will come up with a strategy to implement, which will be discussed either in this issue or another issue in this repo (or possibly on the universal repo).
Thanks for your interested in incorporating universal in the CLI!!!
I'd love to help Mike. I guess anything Node, express/Hapi/koa integration, wouldn't be too bad. Let me know how I can get involved!
Is there a working-group & roadmap for cli/universal integration ?
@Brocco, can you tell how your investigation goes ?
Thanks.
Some news or nothing ?
@pdelorme @choucry13
Universal itself is undergoing some large changes, but essentially all you'll really need is to just create how the server renders your app, if you're using Node check out the universal starter, everything essentially comes from server.ts (https://github.com/angular/universal-starter/blob/master/src/server.ts). Use the starter as a starting point, until we get something concrete in the CLI. Other than some package dependencies, you can get it up and running fairly quickly. Hope that at least helps for now!
thank @MarkPieszak . Me and @pdelorme will see this solution.
Has anybody succeeded yet to get a working implementation of universal on an app created with angular-cli?
I've been trying all day here, no luck... same last week, tried/failed, until I couldn't think about anything else and had to give up. Today again, the same. Really frustrating... I've tried by getting everything from universal-starter, and just remove the part where webpack builds the app (because I have the CLI for that), just need to generate client.js and server.js, somehow. Anyway, no luck, all sorts of errors, and no matter what I've tried, I can't make it work :(
Would be too long of a post to mention all the steps I went through and everything I've tried and all the errors received along the way.
I'd actually just prefer if I could manage to simply "tsc" the client.ts and server.ts, but tried that and also couldn't make it work, I'm going crazy here. Even tried (again) the "Get started" from universal.angular.io would be so simple, if it actually worked, but that gives me the error for which this issue has been created.
I'm starting to think that I will never be able to make it work, it seems so complicated.
Please, I'm almost begging :) does anybody have a working example (here hoping for a simple one, non-webpack)? Or know of a repo somewhere out there that has a working implementation of angular-universal on top of an angular-cli app?
Now that the CLI has moved to Webpack, have you tried it now?
I can try and give it a shot today, want to make sure it's working webpack-wise with the CLI.
@MarkPieszak I did install the webpack version, but I don't know what's happening behind the scenes and how is that different from beta.10 (I just know it uses webpack). I've also never used webpack myself, it's completely new to me, so everything I'm trying is just guessing to me. I wouldn't know where to begin regarding anything webpack related. I also see that there is no webpack.config.js
in the app generated with the webpack version of the cli :| I wonder where it sets up the webpacky things and how does ng build/serve
actually use webpack in the absence of a webpack.config.js
file.
If you have the time to look into it and manage to implement universal on an app generated with any cli version, a brief how-to would be awesome.
I believe the current strategy is for CLI to use webpack behind the scenes, not that it expose webpack. For example, it does not emit webpack config files into a project, and that is intentional.
I think this is a sound strategy. People who want to directly use webpack already have ways of doing so. Just go grab one of the webpack "starter kits" somewhere and copy it and start packing.
However, a consequence of this strategy is that integration with "universal" will need to happen within the CLI project itself. It's not something that can readily be done at an application level when using CLI.
My hope is for a huge payoff: that some months from now, all of our projects which use CLI are automatically and trivially Universal projects.
@kylecordes I hope that too... that we'd just be able to "ng new -universal" and that's it! (optional, of course, so no one can complain)
Until then... still no luck for me, implementing Universal on a cli generated app is yet a mistery to me. I think the universal-starter is too complicated for me, no matter how many times I've tried, I couldn't implement it on top of my angular-cli app (I've also never used webpack, so when trying to implement the universal-starter I'm only kind of guessing on what that webpack.config.js file does, and probably couldn't really manage to tell it to ignore my app - cause that is done with ng build
- and just build the server part).
Anyway, what would be really great is if they had a quickstart that worked. I wish they had a server file in their quickstart that would do what it's supposed to: WORK! :( I mean, first of all - they say "put this in a server.js
" but then, if I try > node dist/server.js
it screams that it doesn't know what the "import" statement is. Then, I've tried to name the file server.ts
and tried tsc path/to/server.ts
, but that just throws a bunch of "Cannot find name" errors. Not to mention that the tsc
command generates js files for each of the app's ts files, which then I had to clean up (cause I can't change the tsconfig.json, the cli is using that. Whish that tsc path/to/file.ts
would actually ignore file related settings in the tsconfig.json
. Anyway, then I've added a reference to browser.d.ts (on cli-beta.10, cause there's no such thing as typings
folder on beta.11-webpack anymore) and finally got to start the node server with that server file, and when trying to access localhost:3000 in the browser, I finally got the error this issue was opened for :(
Node: v6.3.1 (which should be fine, because it's >=4 as I've seen everybody recommends)
I'm thinking maybe I give up javascript,typescript,angular2,html,css... everything! And maybe I go somewhere in the mountains and just live there on berries... that's how frustrating this has become.
I'm quite close to getting the universal starter working with the webpack version of the cli the only barrier being typings.d.ts.
When using the typings.d.ts created by the cli compiling the server side ts generates the errors
ERROR in /Users/marcus/hosts/coco-cli/src/typings.d.ts
(6,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'module' must be of type 'NodeModule', but here has type '{ id: string; }'.
ERROR in /Users/marcus/hosts/coco-cli/src/typings.d.ts
(7,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'require' must be of type 'NodeRequire', but here has type 'any'.
and client errors are
ERROR in [default] /Users/marcus/hosts/coco-cli/node_modules/angular2-universal/dist/node/router/node_platform_location.d.ts:2:25
Cannot find module 'url'.
if I then add the typings.d.ts from the universal starter the same errors.
If I remove what's generated by the cli the server side code compiles but the client then produces the errors.
ERROR in [default] /Users/marcus/hosts/coco-cli/node_modules/angular2-universal/dist/node/router/node_platform_location.d.ts:2:25
Cannot find module 'url'.
ERROR in [default] /Users/marcus/hosts/coco-cli/src/app/app.component.ts:5:12
Cannot find name 'require'.
ERROR in [default] /Users/marcus/hosts/coco-cli/src/app/app.component.ts:6:11
Cannot find name 'require'.
I'm starting to wondering what the merits of typescript and typings are apart from adding extra confusion and complexity
I remember I've read about these errors somewhere. I have no idea about where exactly though... But I can still recall that it was fixed by changing es6
to es5
in libs
inside tsconfig.json
. I think... You could give it a try. But I can't say why it is so. Maybe someone more well-versed could clear things up. And also, tell me if this was it.
That actually makes it worst as you get errors like
ERROR in [default] /Users/marcuswilliams/Hosts/coco-cli/node_modules/rxjs/operator/toPromise.d.ts:9:8
Cannot find name 'Promise'.
ERROR in [default] /Users/marcuswilliams/Hosts/coco-cli/node_modules/rxjs/operator/toPromise.d.ts:10:25
Cannot find name 'Promise'.
ERROR in [default] /Users/marcuswilliams/Hosts/coco-cli/node_modules/rxjs/operator/toPromise.d.ts:10:35
Cannot find name 'Promise'.
@jeffbcross I saw you updated universal in the package.json for the latest CLI webpack version. To what extent is universal being utilized in the existing build?
@goelinsights To create the app-shell
@MarkPieszak Did you get it working ? Its really becoming a pain and stopping me from using Angular in a large project.
We should be releasing Universal for rc5 & 6 soon (it's been a tougher process than we imagined), I'll get back to you as soon as we ship it and I can verify it works with the CLI! :) I completely understand, there's been a lot of change & turmoil in rc-land haha. For now, if you just work on the project as a normal one, you should be able to move everything (in your app folder) into a newly minted cli --mobile
one, once everything is completely integrated between the 2 of us. @ritz078
Thanks @MarkPieszak . that really helps :)
will there be asp.net support on server side?
Any updates of this? Is angular universal usable with the CLI?
@theunreal @ritz078 @goelinsights @dottodot @vinodbhargava @neilhem @vaskgjuri
There is an open PR for the CLI here: https://github.com/angular/angular-cli/pull/2318
I'm not sure exactly when it will be merged, but soon there will be --universal
support :+1:
You can thank @DevCrossNet :sparkles:
any news on this? seems like there's 10 different threads around this, all forwarded on to the next
Still no updates on this? Adding the --universal
flag to the CLI?
We have some trouble to publish it. You can already use it. Check out the universal-webpack branch in my fork. It will be published soon. Sorry that it takes so long.
@devCrossNet will someone comment here when it is published? I'm sure that many (including myself) are waiting on this delicious addition to the cli.
@azjkjensen yes, I will comment here and tell you how to install it. I have to change a lot since it will not be integrated in the angular-cli project. Therefore we have a lot to test in the first release.
@devCrossNet Is it going to be a separate project which will generate angular universal ? And another question. How do i make prodaction folder with server file in to dist folder. Because now if i clone your repo universal-webpack and after run ng build --prod i do not get server file in dist folder there fore i cen not configure package json to run server from the dist.
@goriunov it will be a separate npm package. But it will be always up to date with the angular-cli project. So you have everything from both worlds. It'll work like the angular-cli but with an additional flag --universal
. You should already have a production bundle for the server in ./dist/server.bundle.js
, if not you've found a bug.
@devCrossNet I suppose this is temporary. And ultimately, we will only have one angular-cli package.
I don't know what could have changed so drastically that would also affect the "regular" usage (without the --universal
flag) and needing to be a whole separate package... only difference should be whether or not I want to use the --universal
flag, no?... Or is this "split" because (for a while at least) there will probably be more releases for the universal version (bug fixing/features etc.)...
@MrCroft I planned to have it as a separate channel on angular-cli, like angular-cli@universal
. But the core team has not enough time to review changes that are not part of the core angular-cli project. And they also have not enough time to publish every time I want to publish something new. So they came up with this solution. But with the nextGen of angular-cli it will be much easier to implement things like universal support. So we have to wait for the nextGen to get a better solution. An alternative would be to not publish it and just leave it as a fork and everyone that wants to use it, uses git clone and install it locally.
I published the first version of universal-cli
, you can install it with npm install -g universal-cli
and if you want to create a universal project type ng new <appname> --universal
. Feel free to contribute, file issues, etc.
@devCrossNet Is there a repo for this or is this just the branch you mentioned? Just wondering for bug reporting if I happen to find any.
BTW, Thank you so much, the only thing keeping me from going strictly to angular 2 was the SPA SEO issues and universal solves that as well as the ease of the CLI.
@daygon2007 this is the project page: https://github.com/devCrossNet/angular-cli. have fun! :-)
Hello @devCrossNet, I just checked your universal-cli >) Thank you for work). In generated project we have file polyfills.ts however i have not found any places where we use this file. Should we import it in the client.ts?
And i have not found any way to create issue in https://github.com/devCrossNet/angular-cli.
@goriunov sorry, I did not have enabled the issues. It is now enabled.
@devCrossNet could you clarify what you mean by cli "nextGen"? Since the flow of information is .. less than ideal. Is there some kind of breaking changes coming down the road?
@Renader as the repo of angular-cli says "Prototype of a CLI for Angular 2 applications based on the ember-cli project.". There are discussions about, how can the CLI be more extensible (e.g. universal, mobile). Best would be some kind of plugin system, that you can create a universal plugin and the plugin author has to his job on quality and stuff and not the core team. It should not change the result of the CLI (structure, commands, etc.). It is more a change for developers. But I don't know the big picture. I think it is a difficult topic and they have to do a lot of thinking to create a proper plugin system.
Great to hear we can now use --universal. Is there anywhere we can find out about deploying the resulting project to a remote server (CentOS in my case)? I thought it should be just a matter of running "node server.bundle.js" on the server, but after few hours of trying I'm not so sure anymore.
@code-div do you get an error or something?
@devCrossNet sorry, yes, should've mentioned: "Error: Cannot find module 'angular2-universal-polyfills'".
Would be great if you can create an issue in the universal-cli repo
So is the idea that with universal, the first hit to the app will be fully rendered on the server and sent to the client, which if your needs are for proper SEO meta tags for crawling, these will be present in the payload sent to the client. Then, when you continue to interact with the app, you will be in client mode?
@photostu Yes, and it also helps speed up the first rendering of the page since you get a very small pre-rendered page first, and then you load the js. Making the app snappier.
Hi Guys, I have an angular-cli app which is compatible for AOT compilation. and I want it to have a angular universal support as well. so I just run a command "ng serve --universal" and it working perfectly
My Question is - "Does it mean that my app is working fine for angular universal?"
Any help will be appreciated in advance.
If you're using the Angular-CLI here it doesn't have any aspects of Universal in it just yet, Universal aspects are within the Fork here (https://github.com/devCrossNet/universal-cli). Hopefully to be integrated with this CLI in the future. It is in Alpha though, so you may experience some issues. @shriunyscape
Does anyone have any idea when Universal will be integrated with Angular-cli? I'm looking for a realistic timeline.
Please note that the universal cli fork is going to be abandoned soon ( https://github.com/devCrossNet/universal-cli/issues/101#issuecomment-288464913 ) so it may be not a good idea to start stuff using it now.
@angular/platform-server related PRs: https://github.com/angular/angular-cli/pull/5194 https://github.com/angular/angular-cli/pull/5547
Universal demo from robwormald: https://github.com/robwormald/ng-universal-demo
My attempt to get Universal working in CLI: https://github.com/intellix/angular-cli-server/commits/master
Commit: https://github.com/intellix/angular-cli-server/commit/c2ea1eb21bc88f530cd2fafa57fb1768698eded3
Errors I get when serving via: ng serve --app=server
ERROR Error: The selector "app-root" did not match any elements
at DefaultServerRenderer2.selectRootElement
Commit: https://github.com/intellix/angular-cli-server/commit/0159223ce2e873c8653b07d72d595c455537b213
So I found this commit to universal-cli by FrozenPandaz: https://github.com/devCrossNet/universal-cli/pull/85 which is essentially ng4 and platform-server. I copied some stuff into my angular-cli-server project and this time when I try to serve I get the error:
Tried to find bootstrap code, but could not. Specify either statically analyzable bootstrap code or pass in an entryModule to the plugins options.
Which is because the bootstrap code is inside ng-express-engine.ts, but a check is made for it inside your main file here: https://github.com/angular/angular-cli/blob/master/packages/@ngtools/webpack/src/entry_resolver.ts#L133
--
Judging by the PRs in here and universal-cli, I'd say most of the Universal work is coming from @FrozenPandaz so maybe he knows a little more about what's left to get Universal into CLI :)
Please be patient, it'll take some time. At this time.. the best option is to probably eject from CLI and then use it in place of my client config here: https://github.com/FrozenPandaz/ng-universal-demo/tree/master/webpack
Those 2 PR's are the main bulk of what I think is required to run universal BUILDS through the CLI. A considerable amount still needs to be done to run a dev environment which I have lined up but am waiting for approval of the initial PR's before submitting.
should be highest prio right now
should be highest prio right now
indeed!!!!!!!!!!!!!!!!!
All the available examples, including the awesome work by @FrozenPandaz show how to achieve SSR via some sort of a server (node.js express),
However, I think it's important not to lose track of the case when you'd want to pre-render selected pages and have them available for static web hosting (example: AWS S3).
This is especially important since it's the recommended way of doing SSR:
In fact, it is our recommendation that your first option should be using Angular Universal pre-rendering to generate static HTML files so you don't need any dynamic rendering at run time and everything can be cached on a CDN
I can imagine the build command would look something like this:
ng build --platform=server --pre-render-urls=ssrUrls.json
ssrUrls.json
{
"urls": [
"/",
"/about",
"/contact"
]
}
Based on the reply from https://github.com/angular/angular/issues/13822#issuecomment-285554330 . It sounds like very simple to do the pre-rendering. It would be great if someone can show some example or point out how to do pre-rendering for a cli generated project. Or just do it after call the eject cmd and modify the webpack configure at this stage?
It should be pretty simple to call renderModuleFactory to get your HTML. 4.0 examples should be up at angular/universal repo next week.
I completely agree with @DmitryEfimenko.
Some static pages into /dist
would perfectly fit into the current way how the Angular-CLI works. No custom-server/express.js to mess around with, instead super easy deployments and great scalability.
Can anyone share a timeline on when universal would be available with cli , or at least a current working instructions to enable sever side rendering on cli project ? Looks like https://github.com/devCrossNet/universal-cli is not stable (or building) currently, So what are the options available for a cli project at this stage ?
It's integrating into core. Take a look at platform-server. Rob mentions it in the latest ng-conf keynote
Get Outlook for iOS
On Tue, Apr 11, 2017 at 12:29 PM -0700, "kaleemxii" notifications@github.com wrote:
Can anyone share a timeline on when universal would be available with cli , or at least a current working instructions to enable sever side rendering on cli project ? Looks like https://github.com/devCrossNet/universal-cli is not stable (or building) currently, So what are the options available for a cli project at this stage ?
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub, or mute the thread.
Thanks Vijay.
Tried to use the platform-server as per the keynote , but couldn't get the main.server.ts configured in angular-cli.json without ejecting cli and going back to webpack.
Tried following this https://www.softwarearchitekt.at/post/2017/03/07/server-side-rendering-with-angular-4.aspx , but after ejecting cli , there are multiple issues popping up with webpack (around scss and aot compilation).
Waiting on platform-server support with cli ..
same here
Any updates?
I took a look at this repo example https://github.com/evertonrobertoauler/cli-universal-demo, and it actually worked. I ran into a few issues though. If you're using BrowserAnimationsModule, it'll prevent the server from loading at all. NoopAnimationsModule works, but obviously with less material flair. Another issue is that you can't seem to run it in anything other than prod mode. Either way, it worked and you can still use ng serve for local work.
Thanks @janiukjf for sharing the demo.. Finally I was able to get the ssr working in my proj without ejecting cli by following that example..
@janiukjf I took this demo 1 week ago and it's not working properly as well. For example, AngularFire 2 is not working for SSR with this repo. My entire project tied with firebase and that's why I cannot refuse from it.
@IPRIT Yeah, I'm probably going to have to eject from the cli to get animations working properly. There doesn't seem to be a way to get BrowserAnimationsModule working with this technique since it all uses the same app module.
@janiukjf The problem is, you really don't want to just have a ServerModule inherit from AppModule (if you need to split Browser/Server platform dependencies).
What you want is a Browser module and a Server module (that both import app.module which only has the most common things). Then Browser-app.module has BrowserModule
in it, AnimationsModule etc. Server has ServerModule
, NoOpAnimationsModule etc.
+ app.module (all the most common things)
+ ^ ^
+ browser-app.module server-app.module
Hope that helps!
Check here for an example of how you could be splitting platform logic.
@MarkPieszak Yeah, I assumed as much. I will definitely be working on that as soon as I find some more time. I'll definitely be looking at that example when I do. Thanks for the pointer.
Could someone point out how to get the http calls working during server side rendering ? Requests fail with this error
Response:{
_body:
ProgressEvent:{
type: 'error',
........
status: 0,
ok: false,
statusText: '',
type: 3,
url: null
Do I need to import some extra HTTP provider for SSR calls to work (while using the platform-server library) ?
@kaleemxii you need to provide absolute url to angular http
Thanks @hheexx , however my error was related to the way I was overriding http service in a shared module, after I moved that to main app module, it worked.
Hello everybody, I have an angular 4 cli project and I need to implement SSR through the prerender logic so that I can upload it onto an amazon S3 bucket.
Is there any guide or how-to that I can follow?
Thanks.
Has anyone experimented with this angular-ssr project? I found it through The Unofficial Angular Docs. Sounds like a decent solution for an Angular 4 application...
any news
@MuhammadShaban I got my app working with cli and SSR using several examples. This is the one that worked for me with separate browser and server builds. https://github.com/pquarme/cli-universal-demo
@janiukjf thank you so much, i will try it
@janiukjf is AOT server/client side included in https://github.com/pquarme/cli-universal-demo ?
@vforv Yup. It is. The only weirdness it has is with SCSS compilation on server side, but that is also included. They use gulp to process the sass files and then run webpack to properly process them. I want to spend some time trying to get this to work without gulp, but I haven't made it a priority yet.
@janiukjf how can I check that? I can not find tsconfig-aot.json and rollup files...
Does pre rendering come out of the box with any of the mentioned examples? Would it be possible to render multiple static html/css assets for individual pages with these setups? Now, the only static html page rendered is the index file. I'm using evertonrobertoauler/cli-universal-demo
Tested that repo but not satisfied. Performance are worse than universal-cli, and universal-cli even don't have AOT.
@janiukjf Did you manage to have your app working with cli and SSR even with prerendered AJAX HTTP requests? I checked on https://github.com/pquarme/cli-universal-demo but it's not implementing any prerendered AJAX HTTP requests. Is there any repo showcasing cli with ssr and prerendered AJAX reqs?
Thanks,
G.
@stratio84 I haven't gotten that far yet. I'm using Angular Material, and that repo is breaking most SSR. Until they get a few PRs merged, I can't test all of it without removing a ton of code. That said, I'm using route resolvers for most of my calls. So I can't imagine why it wouldn't pre-render that. If it required calls on the page post init, I doubt it would pre-render them.
@janiukjf The problem is that I need a full prerender so that I can upload my app on an AWS S3 bucket. I'm trying to find an example that uses angular cli but I found none so far. The one at https://github.com/clbond/angular-ssr has an example but it's not using angular-cli. Which repo do you advice me to start from in order to develop a working skeleton?
Thanks,
G.
Found this one: https://github.com/stevermeister/angular-ssr But not tested yet...
@stratio84. With https://github.com/evertonrobertoauler/cli-universal-demo you're at least able to fully aot-render a working application that can be uploaded to an S3 bucket. The only actual static file is the index.html and everything else is compiled angular code that gets loaded in. I've yet to find any solution that renders multiple static pages. @vforv with this setup I'm getting satisfactory performance, not better than the regular aot in angular-cli though.
I can't imagine the performance of each individual technique ever being any better as all of these SSR approaches use essentially the same process. All the code always has to go through the same compiler and use platform-server / browser. The only thing that might actually make a difference is what server it's running on and the complexity of what your app has to do on first load.
@AntonScotte I checked that repo but the code is not implementing any AJAX HTTP call. Are you saying that if i clone that repo and I myself add one call it will be prerendered just by compiling with ng build --aot?
Thanks everybody for the help and sorry for the rookie questions but I have been discovering angular 4 and ssr only since a couple weeks. I'm coming from AngularJS and everything seems quite different :)
@stratio84 Take a look at https://github.com/FrozenPandaz/ng-universal-demo. There's a transferState module that I think is what you're looking for. You'll find the app server file here: https://github.com/FrozenPandaz/ng-universal-demo/blob/master/src/app/server-app.module.ts#L38. It's referencing the TransferState module.
@stratio84 I'm not sure, but in general my application works as normal when I ported over to SSR and I'm using a bunch of observables throughout the app. I'm not keen on AJAX calls, so I don't want to give false hope out if ignorance but, a few quirks had to be delt with to tell angular to execute chunks on the client instead of server side as for example window could not be accessed server side. My guess is that you might be able to do a similar workaround to prevent angular from directly executing the call on the server and wait until the client is ready to go.
@janiukjf client bundle can significantly increase performance... Current size is too big 350KB+... It is wird universal-cli with Angular 2 have better performance that that repo with Angular 4.
On reguler 3G network universal-cli "Hello world" app open for 2 sec but for that repo it taks 5s
@janiukjf I just cloned and build it with aot. Inside the home page it contains an http call to a json whose content is then shown inside the page. However even with aot build the request doesn't get prerendered at build time, It is still issued at runtime. My main goal is to have an app that can be fully prerendered at build time so that when the S3 bucket serve it it is completely static and no elaboration is doing even client side.
Thanks
G.
@vforv universal-cli is also 4 months or more out of date and doesn't seem to be maintained anymore. I wonder how the performance would be if it was brought up to date with the latest code.
@stratio84 If you do get things working the way you want them to, please post back here about it. It'd be interesting to see. Good luck!
@janiukjf the universal-cli project is no longer maintained. I moved further to other projects and @FrozenPandaz wanted to implement universal in the angular-cli. But I don't know the status.
They said angular universal will be maintained by Angular official team when ng4 released. Is there still a problem with angular-cli and universal?
@altugank I think it is not really clear how to use it together. The original plan for the integration was to have some kind of flag that gives you all the power of the cli and make it easy to use angular-universal with different use cases (pre-rendering/re-rendering).
Right now it seems to be a whole bunch of manual steps to get these things to work (not a good DX in my opinion).
@FrozenPandaz: are you still working on the universal/cli integration?
@devCrossNet On usage together, I think if ultimately, it could be like angular-ssr would be great!
About @FrozenPandaz ... I understood https://github.com/angular/angular-cli/issues/1050#issuecomment-289225562 as that he is basically waiting on you to merge his PRs.. (Almost all of the open PRs on universal/cli are from him to you).
Am I mistaken?
Hello, I checked https://github.com/clbond/angular-ssr and tested the example with express for on demand rendering. The problem is that it does not render at build time but only at request time on server side.
It would be really helpful to look at an example that does a full prerender of routes and AJAX requests completely at build time (better if with angular-cli but anything else working would be good too).
Anybody can provide a working repo showcasing these features?
Thanks,
G.
@somombo the universal-cli is no longer maintained. That's the reason why the PRs are not merged. @FrozenPandaz and I decided to leave it like it is in favor of a real angular-cli/angular-universal integration that he is working on. (I already saw a proposal to the team some month ago but I don't know the status)
@devCrossNet I see. Thanks for clarifying.
Looks like PR https://github.com/angular/angular-cli/pull/5194 is where we are at. Seems like that one is necessary to get the rest of it working. Appears to have been some commit activity five days ago. Of course @FrozenPandaz is the best person to comment on all those though.
Looks like #5194 has been merged into master a few hours ago. Where does this leave us?
Leaves us waiting for a release now :)
I think we need https://github.com/angular/angular-cli/pull/5547 too. Somebody should rebase to fix the conflict and write unit test to approve it.
According to @FrozenPandaz it does not depend on #5547. Where do we go from here?
Yes, the other PR (#5194) does not depend on #5547. So now the server bootstrap code is replaced as well.
But the feature what we want to have (interating universal into angular cli) needs #5547 to build the correct bundle for NodeJS.
@kondi Gotcha, thanks!
is this coming soon?
Who owns this? Any update?
UP! It would be really nice to be able to make pre-rendered apps without giving up on the CLI. The CLI is very useful for development.
To wait you can style clone this project : https://github.com/designcourse/angular-seo. Hope I'm saving some lives lol
@glemiere unfortunately, if I add a lazy module into that, it doesn't get rendered server side.
ERROR { Error: Uncaught (in promise): ReferenceError: System is not defined
ReferenceError: System is not defined
Also, I can't figure out how to access cookies server side. Went back and forth between different examples found across GitHub, but they're very different from the example in your link, I can't make anything out of them (plus, most are using a unversal-starter).
Have you managed to make it work with lazy modules or read cookies server side?
angular2-cookie has a working implementation for server side. It involves
having a separate provider for node and using Zone.current
On Sun 18 Jun, 2017, 6:44 PM Marian Stoica, notifications@github.com
wrote:
@glemiere https://github.com/glemiere unfortunately, if I add a lazy
module into that https://github.com/designcourse/angular-seo, it
doesn't get rendered server side.ERROR { Error: Uncaught (in promise): ReferenceError: System is not defined
ReferenceError: System is not definedAlso, I can't figure out how to access cookies server side. Went back and
forth between different examples found across GitHub, but they're very
different from the example in your link, I can't make anything out of them.Have you managed to make it work with lazy modules or read cookies server
side?—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/angular/angular-cli/issues/1050#issuecomment-309277059,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAeZ8SGRnnTAQu7Q05WLCVIsW-I5enBDks5sFSLNgaJpZM4Ixuiz
.
@glemiere I have the same issue as @MrCroft. Is there any solution for lazy loaded modules rendering?
When this feature will be supported?
@Brocco At large scale angular site is taking 30 seconds for first meaningful paint on slower network. Could you please give us a time line for SSR. I don't want to switch from CLI.
Guys, any news?
This feature is really important
@MarkPieszak
@glebmachine as far as I know, there's 1x PR left and it has a very small change before it can be merged: https://github.com/angular/angular-cli/pull/5547
Dear god, i hope it will be done soon!)
any good example right now, how to integrate server side rendering with angular cli?
P.S. I am quite disappointed in support of angular-cli team, it looks like noone cares about this issue
@dimitriy-k and anyone else looking, then the best example I have found for at server side rendered solution with angular cli is this article: https://coursetro.com/posts/code/68/Make-your-Angular-App-SEO-Friendly-(Angular-4-+-Universal)
The biggest issue though, is that the server code is only running through ngc
and not webpack. Therefor all loaders (sass etc.) and environment variables are not passed to the server side code and will not work.
Currently also stuck in same place as @mikkeldamm. Since I'm currently hosting in S3 with a fairly static site, also looking to see if anyone else is just using S3 static site and not EC2/ heroku/ GCP/ Azure/ etc to run a server.
Looking to understand the prerender on build with an S3 upload of post-processed static files (then pushed to Cloudfront). Has anyone seen a good resource/ example on this? Rob Wormald mentioned it as the easier end of the spectrum at ng-conf, but had no luck with angular-ssr and not seeing much documentation on this.
@mikkeldamm yeah, that's a very basic example. Plus lazy loaded modules aren't rendered server side.
I'm eagerly waiting for the CLI implementation... And some documentation and a style guide / best practices.
@wnabil regarding your comment below: that is so much overhead... Having 2 separate processes for server/client build, one with cli/webpack and another with gulp.
If you absolutely must have SSR today, maybe. But I'd wait for the CLI.
_Sent from my Samsung SM-G950F using FastHub_
@mikkeldamm
i am still new to angular universal but i think we can make the integration like here
https://github.com/pquarme/cli-universal-demo
and using gulp we can compile the scss and also the third party libraries with webpack external
this one looks promising:
https://www.npmjs.com/package/angular-ssr
haven't had the time to try it yet tho
So, what the plan about cli ssr support?
I'm waiting it so much :(
@goelinsights I have also S3 and CloudFront serving my ng app. I am planning to use nodejs in a docker container to serve it server side rendered.
@MrCroft
But I'd wait for the CLI.
Waiting from 27th of March (my first comment here) :(
Hey guys, I know it might not feel like it, but the cli team does have intentions on getting us a stable integration of universal into the cli as soon as possible.
I can't remember which of the team members I spoke to during the ngConf angular cli Q&A, but I do remember this being my #1 question for the team and I remember them saying something to the effect of them really wanting to get it added, but that when it does get implemented into a release of the cli, they wanted to make sure that it followed their standard, which is "it just works" - meaning, they don't want to push the feature to an update until they are absolutely confident that it is working and people don't have to worry about repercussions of its usage.
I'm eagerly awaiting this capability as well. Waiting sucks, but sometimes with open source we have to.
I can second what @vegaskev said. I talked to the team at Google I/O this year, and they said very similar things. They are keenly aware of how much people want this. It really does suck having to wait, but it will happen.
Angular CLI team. Don't hurry. We all understand that while we are lying under the sun at the sea side you work hard to make a great product for us. Thank you for that. Better It'l be good, we can wait. We believe in you! And love you of course :heart: :kissing_heart:
The best way is to give an option in cli like
$ ng build --prod --ssr
or $ ng build --ssr
which will build a simple express server server.js
in the dist
directory like in https://www.npmjs.com/package/angular-ssr
In the meantime I think a lot of us would be happy with just documentation
and guidelines on setting things up. Particularly to do with:
1) Lazy loading and SSR
2) Meta tags
3) Sending http status codes like 301, 404, etc from within the module back
up through zone/express
4) preboot and state transition related stuff
5) prerendering static htmls for components/pages that don't rely on
dynamic data, if at all possible
6) optional caching of http/API calls in a server side cache for
pages/components with dynamic data
Not really relevant to the cli, but given that the feature itself has
nearly no documentation, many of us don't even know where to begin. I'll
probably give angular-ssr a try till then. It looks quite promising.
I have almost everything working fine with ng2 but I'm eager to upgrade and
take advantage of the improvements in angular 4. At this rate I'm likely
better off moving to vue or react over this one issue.
On Fri 7 Jul, 2017, 11:27 PM Gopakumar, notifications@github.com wrote:
The best way is to gave an option in cli like
$ ng build --prod --ssr or $ ng buil --prod --ssr
which will build a simple express server server.js in the dist directory
like in https://www.npmjs.com/package/angular-ssr—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/angular/angular-cli/issues/1050#issuecomment-313751047,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAeZ8Z02TLXe_KYfqEuCrC5j_wuxYHpLks5sLnFugaJpZM4Ixuiz
.
@kblestarge i've been using https://github.com/clbond/angular-ssr and works pretty good (even with angular material and other modules)
@stratio84 i dont know how would be possible to have build time rendering as we have assync calls almost everywhere on web..
to be honest.. very happy with @clbond project and as soon as the oficial support for universal comes to angular for SSR, will be quite easy to port this project on top of that!
thanks angular team for the awesome work!
1.3.0-rc.0 contains the Universal/server stuff we were waiting for from FrozenPandaz: https://github.com/angular/angular-cli/releases/tag/v1.3.0-rc.0
Here's an example repository referenced from the PR which implements it: https://github.com/FrozenPandaz/u-cli-app
Will have a play around with it now maybe
Seems documentation has just been added
https://github.com/angular/angular-cli/wiki/stories-universal-rendering
Yeah, a day ago)))
Looks like a great step forward! Are there any instructions on aot pre-rendering? - I remember Rob talking about this at ng-conf (which then leads to pwa => amp pages which should be great for content sites)
Very excited for the lazy loading additions (would be great to finally see cli, lazy loading, universal, Ng Rx store and angular material 2 all playing well together)
Get Outlook for iOS
On Tue, Jul 25, 2017 at 11:10 PM -0700, "Eric" notifications@github.com wrote:
Seems documentation has just been added
https://github.com/angular/angular-cli/wiki/stories-universal-rendering
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub, or mute the thread.
Finally! Yeah)
But what about to support lazy loading?
It seems to fail when the app imports libraries using ES2015 imports, for example @angular/flex-layout
.
Steps to reproduce:
server-test.js
, from step _Testing the bundle_)npm i -S @angular/flex-layout
app.module.ts
, add FlexLayoutModule
to AppModule
imports
ng build --prod --app 1
and rename the main bundle to match the import in server-test.js
"rename-server-main": "renamer dist-server/* --regex --find \"main\\.[^\\.]*?\\.bundle.js\" --replace main.bundle.js"
+ npm i -D renamer
, and update server-test.js to require('./dist-server/main.bundle')
.node server-test.js
It logs the following error:
C:\nw\proto\ng-server\node_modules\@angular\flex-layout\media-query\breakpoints\break-points-token.js:8
import { InjectionToken } from '@angular/core';
^^^^^^
SyntaxError: Unexpected token import
After commenting the FlexLayoutModule
module import, it works again.
I dont think flexlayout
its ready for SSR.. in the angular-ssr
i could make even the angular-material to work but i couldnt make the the flex layout.. check it out
@mariohmol It's just an example of library that we can find in the project and has an ES2015 import
, thus blocking the SSR. I guess many other libraries will have the same module format (using import
), and the issue above would be for any of them. I haven't tried, but we may be able to follow the same steps and replace FlexLayoutModule by another lib module with import
. (But the MdButtonModule from material does not cause the issue.)
Good to know that flex-layout would have blocked SSR anyway after the import
issue, thanks for the link. But I didn't even reach this error (document, window...), it is failing before.
EDIT: Angular material seems to also use ES2015 import
, so I'm not clear about why flex-layout's import is not tolerated by Angular CLI SSR, but material's is.
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 I guess we could open the issue in each repo, for instance i found this about ng-bootstrap
I think this is related to the build system, use webpack to make the transpile of your project
@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
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.
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.
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?
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 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 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.
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.
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
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!`);
});
Universal seems to be working pretty well now in 1.3. Any idea on when lazy loading will be supported though?
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 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'}
]
}
};
@suau https://github.com/angular/angular-cli/issues/1050#issuecomment-318672196:
It seems like the
styles
andscripts
from theangular-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?
Do you have any updates about support lazy loading?
@PSTime you may find this useful
https://github.com/angular/universal/tree/master/modules/ng-module-map-ngfactory-loader
https://github.com/angular/universal/tree/master/modules/ng-module-map-ngfactory-loader
does seem to work thanks
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 I haven't tested it yet.. but perhaps @FrozenPandaz or @intellix may be able to provide some guidance. Ref #6913 #7107
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.
I'm also do https://github.com/angular/angular-cli/wiki/stories-universal-rendering step by steps.
But for now i've got following error:
/node_modules/@angular/flex-layout/flexbox/api/class.js:18
import { Directive, ElementRef, Input, Renderer, Renderer2, IterableDiffers, KeyValueDiffers } from '@angular/core';
^^^^^^
SyntaxError: Unexpected token import
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.eO38 (dist-server/main.bundle.js:1:1140643)
at l (dist-server/main.bundle.js:1:149)
I'm also trying to using ts-node
with --ignore false
, but it isn't works for me.
what does you tsconfig.server.json
look like?
This is my tsconfig.server.json.
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"module": "commonjs",
"baseUrl": "",
"types": ["node"]
},
"exclude": [
"test.ts",
"*/.spec.ts"
],
"angularCompilerOptions": {
"entryModule": "app/app.server.module#AppServerModule"
}
}
ok just wanted to check you had "module": "commonjs"
as that error usually means something has compiled to es2015
on the server side which doesn't work in nodejs.
Is your tsconfig
in angular-cli.json
pointing to this file for the server settings?
yes,
This is my angular-cli.json file.
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": {
"name": "appName"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.app.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.css",
"../node_modules/font-awesome/css/font-awesome.css",
"../node_modules/devextreme/dist/css/dx.common.css",
"../node_modules/devextreme/dist/css/dx.light.css",
"styles.css",
"assets/theme/css/style.css",
"assets/styles/step-application.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/bootstrap/dist/js/bootstrap.js"
],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
},
{
"platform": "server",
"root": "src",
"outDir": "dist-server",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.server.ts",
"test": "test.ts",
"tsconfig": "tsconfig.server.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.css",
"../node_modules/font-awesome/css/font-awesome.css",
"../node_modules/devextreme/dist/css/dx.common.css",
"../node_modules/devextreme/dist/css/dx.light.css",
"styles.css",
"assets/theme/css/style.css",
"assets/styles/step-application.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/bootstrap/dist/js/bootstrap.js"
],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"lint": [
{
"project": "src/tsconfig.app.json"
},
{
"project": "src/tsconfig.spec.json"
},
{
"project": "e2e/tsconfig.e2e.json"
}
],
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"component": {}
}
}
Try removing the scripts from your server settings
"module": "commonjs"
helps, now i have to fight with 3rd party packages)
Do you have any ideas if angular cli universal rendering can be used with ASP.NET Core as implemented by @MarkPieszak in Angular universal with ASP.NET Core?
I could successfully get server bundles with CLI. But as soon as I consume main.bundle in Microsoft.AspNetCore.SpaServices.Prerendering.Prerenderer.RenderToString(...) it throws an error that webpackJsonp function is not available. It is defined in inline.bundle and it is used window object here, but window object is not available on the server side. I am not sure if/how it works with .NET Core. Any ideas?
@KhalipskiSiarhei you can try import it function from inline..bundle.js, that has been generated after ng build / ng build --prod.
or try import 'dist/inline..bundle.js'
I haven`t tried it, might be work
@PSTime I am not sure how it is possible to import inline.bundle in server ASP.NET Core environment: in Microsoft.AspNetCore.SpaServices.Prerendering.Prerenderer.RenderToString(...) it is possible to pass one module only, which in fact is main.bundle. Furthermore, inline.bundle is created for browser environment because it contains document.getElementsByTagName, document.createElement, window references which are not available in server environment.
If it helps i have a small demo showing Universal working in the CLI with both prerendering
and express
scenarios and Lazy Loading here https://github.com/Toxicable/universal-starter/tree/cli
Just run npm run build:prerender
or npm run build:dynamic
and inspect the /dist
folder to see how my implementation works.
Feel free to ping me on the Angular Gitter with @Toxicable if you have any questions https://gitter.im/angular/angular
@Toxicable thanks, I will look at it. For now we still use CLI for client bundles and webpack for server bundles and it is not ideal...
https://github.com/angular/angular-cli/issues/1050#issuecomment-322974848
... angular cli doesn't generateLAZY_MODULE_MAP
(I have added platform=server), do you have any suggestion ?
@PSTime I can confirm that I also have not been able to import LAZY_MODULE_MAP
and I dont see it anywhere in the build output.
I suggest filing a separate bug on this @angular/cli repo..
_Be sure to reference the @nguniversal/module-map-ngfactory-loader instructions._
@somombo what version of the CLI? you need v1.3+ for LAZY_MODULE_MAP
In all of the testing i've done it's always worked like so
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require(
./dist-server/main.${hash}.bundle);
@Toxicable Thank you for this!
Best implementation I've found so far that I could simply make work without banging my head against the wall or getting errors I couldn't even understand :) Also, first implementation that works with lazy loaded modules.
I am curious though, what will the final official implementation be... I mean how will the CLI do it, by using only a command / argument when creating and when building the app...
Do you have any examples for things such as:
?
@MrCroft as far as I know I don't think it will change too much from how it looks now.
Things like the prerender.js script I have and the server.js are very much things that the domain should provide rather than the CLI, therefore in that regard I don't think the CLI can provide much more.
As for cookies I havn't looked at how this will work yet, I'll put that on my list though, if you want to make an issue/proposal on https://github.com/angular/universal for it that would be appreciated.
Your second point is referring to a concept called StateTransfer, this is the process of storing your state on the server then transferring it to the client and reusing it.
I am currently working on a proposal for this and subsequently a PR
Is universal now part of angular client or not yet? If not, is there any timeline when it could be?
@ennyta Yes, take a look at universal-starter to see it in action. I'll be updating the docs here in the CLI for it as well.
@mrcroft You'll still have to run and bundle the server things yourself, it won't be part of ng serve, that will still produce only the client bundle. The concept of universal implies the server aspect, so there needs to be that separation.
Also this gives freedom to any type of node server someone wishes to use, hapi koa express etc.
As for cookies, in the server you'd have to handle it yourself by passing in the req object to the providers[] and then use Dependency injection to have the server use those, while the client gets them from document.cookies.
Hope that helps a little bit!
Also, right now you can manually create or use one of the TransferHttp examples we have, but soon it will be part of Core that will (optionally) handle it, if you tell it to do it for a certain GET call.
Thanks @MarkPieszak
Is there a way to test somehow universal build from dist-server locally?
@ennyta If you're using https://github.com/angular/universal-starter and in the cli
project then you can use npm run serve:static
for static rendering ( aka prerendering) or
npm run serve:dynamic
for dynamic rendering (using express)
to see how it looks as if you were running on a prod server but locally
@Toxicable , I am in client and have two folders following https://github.com/angular/angular-cli/wiki/stories-universal-rendering.
Is there a way to test dist-server locally?
@ennyta are you planning on doing prerendering or using Express/aspnetcore to do dynamic rendering?
@Toxicable Trying to do prerendering, managed to run it and now getting error like this:
import { Injectable } from '@angular/core';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:53:10)
at Object.runInThisContext (vm.js:95:10)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.sZvN (C:\Users\ana\workspace\foodfest\foodfest-client-clidist-server\main.ed8dace87ce02020841a.bundle.js:1:859271)
Any idea if it is fixable? I see several people in this topic run into them, but I don't see if there is a solution for it.
This seems to have been removed: https://github.com/Toxicable/universal-starter/tree/cli (I get a 404).
I guess we can use the universal-starter/cli - it was updated like 10 days ago - but there are quite a few differences in the server.js and prerender.js files (compared to what @Toxicable 's repo had) - and maybe other files I haven't checked yet (I think I can say that, to me, they're almost like plain "text" differences, because I have no clue about Node development whatsoever).
Should we consider that the CLI folder in the universal-starter is (and will continue be) the most up-to-date example of Universal implementation on a CLI generated app?
@gdi2290 About prerendering, I've read that "_it renders your application and replaces the dist index.html with a rendered version._". What is that useful for? I mean, we don't only have a root (home) page. Should we manually go over all the routes and generate a static html file for each possible route? And is this done by simply replacing the value of the url
key in the renderModuleFactory
options? But, even so... we might have dynamic routes or route params and query params, which would be very difficult (if not impossible) to take into account in the prerender.js script to generate all possible html content files for all the possible routes/route params/query params combinations (not to mention that, for the route params, the actual values will most probably come from a database). I'm completely failing to understand what prerendering is about... I must be missing something, I guess it must have it's use... I think that I'm just failing to see what that is? If not, then it seems to be an overkill to implement. The way to go would then be dynamic and I'm sure that a Node developer would also be able to easily cache whatever content is generated on the first request and use that for future requests.
EDIT:
Alright, so I've got my answer below. I understand that prerendering is more suitable for apps in which generating the content doesn't rely heavily on dynamic params (which most probably correspond with identifiers in some sort of server-side database). And for that, we're better off with dynamic rendering (and some sort of caching, of course). Thank you @Toxicable
@ennyta See this issue for for information on that issue https://github.com/angular/angular-cli/issues/7200
@MrCroft My demo has been merged into https://github.com/angular/universal-starter/tree/master/cli
The example there shows only the /
route being rendered but I have a tool in the works that will allow you to dynamically generate prerenders for every static route in your app see: https://github.com/angular/universal/pull/778 or https://github.com/Toxicable/universal/tree/routes-ls
for more about that.
As for dynamic routes with params, they cannot be easily prerendered, you'd be best using one of the dynamic rendering engines we have, either the Node one for aspnetcore one, which will render your app on the fly meaning it can use all the params that come along with the request
@MarkPieszak
As for cookies, in the server you'd have to handle it yourself by passing in the req object to the providers[] and then use Dependency injection to have the server use those, while the client gets them from document.cookies.
Since your comment, I've been searching back and forth for an actual example, but couldn't find one. So, I've blindly managed to do it after reading different issues/browsing through different repos, with this in my app.server.module.ts
file:
// ...
import { Request } from 'express';
import { REQUEST } from '@nguniversal/express-engine/tokens';
export class RequestCookies {
constructor(@Inject(REQUEST) private request: Request) {}
get cookies() {
return !!this.request.headers.cookie ? this.request.headers.cookie : null;
}
}
@NgModule({
imports: [
// ...
],
providers: [
MyCustomCookieService,
{ provide: 'req', useClass: RequestCookies }
],
bootstrap: [AppComponent]
})
export class AppServerModule {}
While also providing a dummy { provide: 'req', useValue: null }
in my app.module.ts
(that runs in the browser). Then, in my MyCustomCookieService
I inject this: @Inject('req') private readonly req: any
and simply check, if it's null
then I use document.cookie
, else I use req.cookies
.
It does work, but I have to ask: is this exactly what you had in mind? Am I doing it the right way?
Also, should I be comfortable with importing something from express
in my Angular code?
Also, right now you can manually create or use one of the TransferHttp examples we have
Where can I find such an example? And/or some documentation to help me understand how to accomplish that?
I think this would be the last thing needed for me to suggest going away from php and go for Node/Angular on a project that is planned for a complete rewrite anyway :)
So, since 5.0.0-rc.0 (if I'm not mistaking), TransferState comes with Angular.
Regarding https://github.com/angular/angular-cli/issues/1050#issuecomment-328584662 by @gdi2290:
the cli probably needs to include nodeExternals and whitelist angular modules that way webpack can read the es6 module syntax
I have experienced the same issue when trying to use ng-bootstrap on with universal.
Does anyone know if there is an open issue for the above (I can't seem to find one)?
@hansl / @filipesilva ... if there isn't one, should there be?
Can be closed since the CLI does work with Universal
https://github.com/angular/angular-cli/wiki/stories-universal-rendering
@MrCroft nicely done, yes that's a great way to get it! Yeah you're fine, you could also just do your own interface for it since you know the exact pieces you want. Either way is fine, since this is all in the server render anyway! 👍
@somombo
I am experiencing the issue to use ng-bootstrap on with universal. An open issue is here
https://github.com/ng-bootstrap/ng-bootstrap/issues/858
Let me know if you found a way out of it!
@itstyro I "fixed" my issue by basically not using ng-bootstrap i.e. forked their bit of code that i needed, and incorporated that directly into my project.. lol
Yeah, apart from the node externals outlined above, I'm still finding a variety of problems with the way angular-cli builds the server aspect of the project.
For example in my main.server.ts
, I apparently cannot have access to the __dirname
global variable.. I use process.cwd()
instead but they are actually not exactly the same thing.
Also in the main.server.ts
there is an error if you do not export the AppServerModule
... I dont want to have to do this because I use my main.server.ts
file as the file where I invoke the renderModuleFactory()
function.. not in a seperate server.ts
as is suggested in the universal cli story.
Closing as @Toxicable correctly mentioned CLI does work with Universal.
This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
_This action has been performed automatically by a bot._
Most helpful comment
should be highest prio right now