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

Universal server bundle is not working properly

Open chrillewoodz opened this issue 9 years ago • 80 comments

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request

Versions.

@angular/cli: 1.3.0-rc.1 node: 6.10.3 os: darwin x64

Repro steps.

Follow these steps here:

https://github.com/angular/angular-cli/wiki/stories-universal-rendering

Add https://github.com/ngx-translate/core to the app.

Build a server bundle.

Test it and you will see the error below.

The log given by the failure.

<some-excluded-path>/ng-boilerplate/node_modules/@ngx-translate/core/src/translate.store.js:1
(function (exports, require, module, __filename, __dirname) { import { EventEmitter } from "@angular/core";
                                                              ^^^^^^
SyntaxError: Unexpected token import
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    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.17 (<some-excluded-path>/ng-boilerplate/dist-server/main.75d7fa7aeab5f9b24f61.bundle.js:1:6560)
    at e (<some-excluded-path>/ng-boilerplate/dist-server/main.75d7fa7aeab5f9b24f61.bundle.js:1:149)
    at Object.2cGb (<some-excluded-path>/chrillewoodz/ng-boilerplate/dist-server/main.75d7fa7aeab5f9b24f61.bundle.js:1:7952)
    at e (<some-excluded-path>/ng-boilerplate/dist-server/main.75d7fa7aeab5f9b24f61.bundle.js:1:149)
    at Object.Zq8w (<some-excluded-path>/ng-boilerplate/dist-server/main.75d7fa7aeab5f9b24f61.bundle.js:1:28947)
    at e (<some-excluded-path>/ng-boilerplate/dist-server/main.75d7fa7aeab5f9b24f61.bundle.js:1:149)

Desired functionality.

Basically the issue here is that node is resolving the wrong module. It's looking inside of the node_modules folder instead of in the vendor file in the server bundle.

Mention any other details that might be useful.

You can download a project with these steps already done:

https://github.com/chrillewoodz/ng-boilerplate/tree/universal

So simply run npm run universal and you will see the error.

chrillewoodz avatar Jul 29 '17 11:07 chrillewoodz

I've been doing a bit of investigation on this the last few days trying a few solutions but havn't come up with anything that'll do it easily.

Just to reiterate the actual issue here; The Library being used is for packaged/formatted correctly. For Universal to be able to use a node package is must be commonjs formatted, meaning that it uses require not import since node does not currently support esm modules (import/export). Which means this is not an issue with the CLI, it's an issue with the libraries not packaging their modules correctly.

Work around i've tried: require('import-export')

  • This module just dosen't support all the right syntax for to be useful here.

Node nightly build

  • While node does actually have inital experimental support for esm modules as you can see here https://github.com/nodejs/node/commit/c8a389e19f172edbada83f59944cad7cc802d9d5 after trying their latest nightly build: https://nodejs.org/download/nightly/ it dosen't appear to be apart of node just yet

re-packaging libs

  • I had some success with this: I was able to use tsc to override libs into the correct commonjs format and successfully used that lib in a Universal project. However this is not a good solution at all, it worked for the lib I was testing on but I don't know if it will work for all, and it's a pretty ugly lots of scripts

From my investigations my conclusion is that the best way to work around this is getting libraries to correctly format their packages so that they can be consumed in a node environment without issue

Toxicable avatar Sep 12 '17 02:09 Toxicable

Thanks for looking into this Toxicable

Are you saying that there is no intention for the angular/cli team to allow packaging of 3rd party node_modules imported into a project to run using Angular Universal and that library maintainers will need to convert all packages to commonjs format for distribution in order for them to be used in server side rendering? Because that's a pretty big ask of the vendors, and will, for a team like ours who are using multiple vendor packages, mean we won't be able to go live with our Angular Universal project for potentially months whilst the 3rd parties sort this out

dannypritchard avatar Sep 12 '17 10:09 dannypritchard

Not to mention a lot of third party authors are lazy and don't care. So it would require a pull request from an outsider and that is an even bigger ask.

chrillewoodz avatar Sep 12 '17 10:09 chrillewoodz

@dannyrevenant Please don't twist what i've said into your own opinion, No that is not what I'm saying.

My words are only of my own opinion, I do not speak on behalf of any groups, I am just a regular dev that enjoys contributing to Angular and surrounding communities, most notably Universal as of recent.

As for what the CLI team can do; The CLI does support importing modules from npm into a Universal project, take Material for example, that works with Universal fine since it's correctly packaged, exemplifying that this isn't an issue with the CLI, instead an issue with the 3rd parties packaging format. However I believe there is some webpack magic that they might be able to configure to allow for importing incorrectly formatted packages but it's not obvious, simple or a good solution, I did not investigate this route since I was not looking for a solution by changing webpack config.

For your mention on packaging formats; no I am not suggesting that libs package their packages solely for Universal, if you would take some time to lookup how libs should be distributing packages then you'd find that you can and should distribute your package in multiple formats so that different formats can be correctly resolved for different situations.

The best thing you can do to getting a resolution to this issue is ask maintainers of the projects with incorrect packaging formats to correct it, or better yet, whip up a PR youreself, I'm sure they'll appreciate it.

Toxicable avatar Sep 12 '17 10:09 Toxicable

At the moment no guidelines were provided regarding the "packaging format" making a lib working with Angular Universal. If someone could write these guidelines, I would be happy to help filling these guidelines and provide PRs to some libs to move things along. Most of Angular application needs Universal working to go live, we need to fill this SSR gap as soon as possible. @Toxicable do you have at least some bullet points to provide as you deeply investigate the problem? Thank you for your clear explanations by the way

stephanegg avatar Sep 12 '17 13:09 stephanegg

@stephanegg See here for guidelines https://docs.google.com/document/d/1CZC2rcpxffTDfRDs6p1cfbmKNLA6x5O-NtkJglDaBVs/preview here for a lib quick start which does the right format https://github.com/filipesilva/angular-quickstart-lib and here for a tool which can output a lib in the right format https://github.com/dherges/ng-packagr

Toxicable avatar Sep 12 '17 21:09 Toxicable

Small update here, looks like node has actually released support behind the flag --experimental-modules on v8.5 which was released today https://nodejs.org/en/blog/release/v8.5.0/

So I attempted to run Universal using this flag but ran into a few issues

  • You cant use import and require in the same file

When using Node's implementation of esm your files must be have the extension .mjs for Node to resolve them, meaning that Libs would have to be packaged in another format before you can take advantage of this feature. It will not be a in-place fix

Which reaffirms my point from earlier that:

the best way to work around this is getting libraries to correctly format their packages so that they can be consumed in a node environment without issue

Toxicable avatar Sep 12 '17 22:09 Toxicable

More investigation!

So I think I have something more definitive this time. I noticed that a lot of the packages had UMD bundles, however for some reason they were not being resolved into the Universal application. TLDR: libs that don't produce a FESM build casue cli to produce deep imports where the umd bundle cannot be resolved.

I made a sample repository here showing casing 2 libs. lib1 - a properly formatted lib which can work with universal without problem lib2 - the average kind of lib that you see which runs into Universal issues

The big difference between them is that lib2 will produce a build output where the JS files that use import/export are not concatenated together or in other words are not flat es modules, lib1 does produce a flat esm build.

If you run the demo with the command below (sorry about all the dependency installs) then you'll notice that lib2 throws the error we've seen so much in this thread.

SyntaxError: Unexpected token import

Well if you take a look at app/dist/dist-server/main.bundle.js and a ctrl + f you'll see that there have 2 entries: require("lib2/src/my-module") and require("lib1") AHA! Now we're getting somewhere. So we know that require("lib1") will resolve to the umd bundle but a deep import like require("lib2/src/my-module") has no option to be to resolve the es module, therefore casuing our issue!

What can be done?

  • As I stated above the best way to fix this issue is for library owners to distribute packages in the correct format, which as I has discovered includes a Flat ES Module option.
  • There may be something the CLI can do to avoid producing these deep imports but I have no knowledge of that side of their build system. @hansl Any idea if something can be done?

https://github.com/Toxicable/universal-deep-import

cd lib1 && yarn && cd ../lib2 && yarn && cd ../app && yarn && npm run build && npm run build:static

Toxicable avatar Sep 15 '17 08:09 Toxicable

Hi, I have no problems with all the steps starting from "npm run start", but on last step "npm run server" (means - node dist/server) my server do nothing with no erros http://prntscr.com/glippe? Can somebody help me with that?

here is my repo https://github.com/genyklemberg/Universal_Project

genyklemberg avatar Sep 15 '17 14:09 genyklemberg

One workaround for now is to basically make your server.js file a TypeScript file, and have Webpack setup to process /.ts$/ included your externals, which are things like node_modules / etc.

Take a look at the comment I made here for more info: https://github.com/angular/universal-starter/issues/428#issuecomment-331558400

Hopefully we can have this as an example in the universal-starter CLI demo as well soon.

MarkPieszak avatar Sep 22 '17 20:09 MarkPieszak

I followed @MarkPieszak 's example, and after adding transferState and transferHttp to prevent XHR requests happening twice, I have SSR/universal up and running near flawlessly on my small project. A lot of typeof window checks because I was in a hurry, but it works!

Here's the repo and demo for reference.

sumanbh avatar Sep 25 '17 18:09 sumanbh

I had this issue with @angular/service-worker, removed service worker from the project and SSR seems working ok. Then tried @Toanzzz 's workaround and found repack bundle size increased a lot:

02/10/2017 12:17 p.m. 45,830 main.bundle.js 02/10/2017 12:17 p.m. 1,180,153 main.repack.bundle.js

Is this normal? Then got error like TypeError: Cannot read property 'subscribe' of undefined

bob-lee avatar Oct 01 '17 23:10 bob-lee

Hey. @MarkPieszak solution works fine (as seen in universal starter) but it has one problem. if you are working with angular i18 for translation and aot, the translations are part of the compiled html. in @MarkPieszak solution, the server.js output file includes all the htmls inside and therefore makes it impossible to create few packages for different language. @AnthonyNahas solution solves the problem specifically for each package during the package download time and by that allows working with i18 inside universal. you can check the solution here: https://github.com/SebastianM/angular-google-maps/issues/1052 Thanks Anthony

yosigolan avatar Oct 09 '17 14:10 yosigolan

Yes you'll have to dynamically pass the language or set it to a specific one and output directory if you're going the prerender route during Build time.

If you can post code in here for others to use 😀

MarkPieszak avatar Oct 09 '17 14:10 MarkPieszak

hope someone help to fix this issue, this is the only reason my application cannot go live

hiepxanh avatar Oct 13 '17 11:10 hiepxanh

add whitelist to angular-cli.json

webpack has an ignore piece, may be it time that we add this to angular-cli.json for build?

externals: [nodeExternals({
  whitelist: [

]

hiepxanh avatar Oct 14 '17 10:10 hiepxanh

Can you update to the latest universal-starter? Using a server.ts file gives you the ability to have your own webpack file (when making that server bundle) so you'll be all set 😀 @hiepxanh

MarkPieszak avatar Oct 14 '17 14:10 MarkPieszak

@MarkPieszak thanks you for your suggestion, I'm successful at creating webpack config. That so cool :)

hiepxanh avatar Oct 14 '17 15:10 hiepxanh

This all seems to work locally, but for some reason when pushing to Heroku I get errors with an output ending in:

remote:        > [email protected] webpack:server /tmp/build_79972feb1473bd61c73534b35e518785
remote:        > webpack --config webpack.server.config.js --progress --colors
remote:
remote:        Hash: ba54fc3daffc6e4050ee
remote:        Version: webpack 3.7.1
remote:        Time: 7982ms
remote:        Asset     Size  Chunks                    Chunk Names
remote:        server.js  3.69 MB       0  [emitted]  [big]  server
remote:        [58] ./src lazy 160 bytes {0} [built]
remote:        [91] ./server.ts 2.03 kB {0} [built]
remote:        [183] ./src 160 bytes {0} [built]
remote:        [189] (webpack)/buildin/module.js 517 bytes {0} [built]
remote:        [202] ./dist/server/main.bundle.js 9.82 kB {0} [built]
remote:        + 201 hidden modules
remote:
remote:        ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts
remote:        [tsl] ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts(3,1)
remote:              TS2304: Cannot find name 'describe'.
remote:
remote:        ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts
remote:        [tsl] ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts(4,3)
remote:              TS2304: Cannot find name 'beforeEach'.
remote:
remote:        ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts
remote:        [tsl] ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts(11,3)
remote:              TS2304: Cannot find name 'it'.
remote:
remote:        ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts
remote:        [tsl] ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts(14,5)
remote:              TS2304: Cannot find name 'expect'.
remote:
remote:        ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts
remote:        [tsl] ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts(16,3)
remote:              TS2304: Cannot find name 'it'.
remote:
remote:        ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts
remote:        [tsl] ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts(19,5)
remote:              TS2304: Cannot find name 'expect'.
remote:
remote:        ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts
remote:        [tsl] ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts(21,3)
remote:              TS2304: Cannot find name 'it'.
remote:
remote:        ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts
remote:        [tsl] ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/src/app/app.component.spec.ts(25,5)
remote:              TS2304: Cannot find name 'expect'.
remote:
remote:        ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/e2e/app.po.ts
remote:        [tsl] ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/e2e/app.po.ts(1,38)
remote:              TS2307: Cannot find module 'protractor'.
remote:
remote:        ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/e2e/app.e2e-spec.ts
remote:        [tsl] ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/e2e/app.e2e-spec.ts(3,1)
remote:              TS2304: Cannot find name 'describe'.
remote:
remote:        ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/e2e/app.e2e-spec.ts
remote:        [tsl] ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/e2e/app.e2e-spec.ts(6,3)
remote:              TS2304: Cannot find name 'beforeEach'.
remote:
remote:        ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/e2e/app.e2e-spec.ts
remote:        [tsl] ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/e2e/app.e2e-spec.ts(10,3)
remote:              TS2304: Cannot find name 'it'.
remote:
remote:        ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/e2e/app.e2e-spec.ts
remote:        [tsl] ERROR in /tmp/build_79972feb1473bd61c73534b35e518785/e2e/app.e2e-spec.ts(12,5)
remote:              TS2304: Cannot find name 'expect'.

Reproduction: https://github.com/intellix/angular-cli-universal/commit/01cd507a3706c9e884d67e3e2b245fe52fdb38ed

intellix avatar Oct 17 '17 12:10 intellix

Investigated the above with @Toxicable a little in gitter. Worked out that the reason why it fails on Heroku only is because when you push code, it only installs "dependencies" and not the "devDependencies" so it's missing some types that are only installed on dev installs:

"@types/jasmine": "~2.5.53",
"@types/jasminewd2": "~2.0.2",
"@types/node": "~6.0.60",

Could be a deeper issue that webpack.server.config.js is reading the spec.ts/po.ts files but I'm not too good at webpack to understand why it does that

intellix avatar Oct 18 '17 10:10 intellix