Universal server bundle is not working properly
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.
Just tried to use import-export, it passes the error place but gives another error:
/node_modules/@angular/compiler/bundles/compiler.umd.js:19601
("ort * as " + prefix + " = require("" + importedModuleName + "");"));
^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected string
Here is the workaround that I'm currently using in my project: recompile the server output with webpack so that other 3rd party libs got transpile to commonjs for node to read
- Add webpack to devDependencies:
npm i webpack --save-dev - Add minimal webpack config
// webpack.config.js
const hash = getHash();
const input = `./dist-server/main.${hash}.bundle`;
const output = `./dist-server/main.repack.${hash}.bundle.js`;
module.exports = {
target: 'node',
entry: input,
output: { filename: output, libraryTarget: 'commonjs' },
}
function getHash() {
const fs = require('fs');
const path = require('path');
const files = fs.readdirSync(`${process.cwd()}/dist-server`);
const mainFiles = files.filter(file => file.startsWith('main'));
return mainFiles[0].split('.')[1];
}
- Target the new compiled file
// server.ts
//const AppServerModuleNgFactory = require(`./dist-server/main.${hash}.bundle`).AppServerModuleNgFactory;
const AppServerModuleNgFactory = require(`./dist-server/main.repack.${hash}.bundle`).AppServerModuleNgFactory;
- Append webpack build step after server build
// package.json
//"universal": "ng build --prod && ng build --prod --app 1 && ts-node server"
"universal": "ng build --prod && ng build --prod --app 1 && webpack -p && ts-node server"
Hope it help
@Toanzzz I'm going to try your workaround now. One comment: by using --output-hashing=none you can avoid getHash() function, cause bundle name is always main.bundle.js.
if you are using webpack, just whitelist the package causing import syntax error using webpack's externals property. Let ts-loader compile the package.. not the best workaround but it works for me! I had the same issue when using ngx-cookie package. seems like these packages are using ES6 modules syntax while Node.js still uses common.js module syntax.
e.g:
const webpackNodeExternals = require('webpack-node-externals');
...
externals: [webpackNodeExternals({ whitelist: [/ngx-cookie/] })],
...
Hope it helps..
I tried workaround mentioned by @Toanzzz and quickly ran into this exception:
reflect-metadata shim is required when using class decorators
I tried importing the reflect-metadata package which seemed to help with this issue, but I quickly ran into another one: Cannot read property 'subscribe' of undefined.
I also tried the solution supplied by @harshes53, but this one didn't work at all to me and once again I got syntaxt error on the import token.
At this point I called it quits - this issue is quite frustrating and I was even considering dropping use of angular-cli for the sake of some seed project which had universal support built-in. I'm still evaluating Angular 4.x and CLI, so I'm not working under the time pressure, but having such issues with integration of 3rd party libraries is a major concern to me at this point.
Anyone has some other ideas how to resolve this?
Just tryied @Toanzzz and @harshes53 solutions and I finally received this exception:
$. /node_modules/.bin/ts-node server
<some-excluded-path>\node_modules\zone.js\dist\zone-node.js:365
callback.apply(applyThis, applyArgs);
^
TypeError: Cannot read property 'create' of undefined
at <some-excluded-path>\packages\core\src\application_ref.ts:365:1
at ZoneDelegate.invoke (<some-excluded-path>\node_modules\zone.js\dist\zone-node.js:365:26)
at Object.onInvoke (<some-excluded-path>\node_modules\@angular\core\bundles\core.umd.js:3922:33)
at ZoneDelegate.invoke (<some-excluded-path>\node_modules\zone.js\dist\zone-node.js:364:32)
at Zone.run (<some-excluded-path>\node_modules\zone.js\dist\zone-node.js:125:43)
at NgZone.run (<some-excluded-path>\node_modules\@angular\core\bundles\core.umd.js:3853:69)
at PlatformRef_._bootstrapModuleFactoryWithZone (<some-excluded-path>\packages\core\src\application_ref.ts:363:1)
at PlatformRef_.bootstrapModuleFactory (<some-excluded-path>\node_modules\@angular\core\bundles\core.umd.js:4509:21)
at renderModuleFactory (<some-excluded-path>\node_modules\@angular\platform-server\bundles\platform-server.umd.js:2405:39)
at Object.<anonymous> (<some-excluded-path>\server.ts:16:1)
at Module._compile (module.js:570:32)
at Module.m._compile (<some-excluded-path>\node_modules\ts-node\src\index.ts:392:23)
at Module._extensions..js (module.js:579:10)
at Object.require.extensions.(anonymous function) [as .ts] (<some-excluded-path>\node_modules\ts-node\src\index.ts:395:12)
at Module.load (module.js:487:32)
@mrwogu do you have a repo where I can re-produce this and help you fix it?
Here's a universal project with ngx-translate added to demonstrate the import error. Neither of the work arounds above worked for me either.
https://github.com/vanaio/preRenderImportError
same issue with here with ng-bootstrap
Same Issue .Any good suggestions ?
i fix similar issue with another npm module (@ngrx). take a look to my solution (only as work around)
Same issue. @hansl any updates or ETA? @AnthonyNahas's answer is a good work around
@AnthonyNahas I can't open your link to know how you sloved it , can I have other link to slove issue of npm module ?
@lichunbin814 the href is wrong in @AnthonyNahas comment. https://github.com/ngx-translate/core/issues/581#issuecomment-326256510
@stephanegg thank u @lichunbin814 fixed the url too
@kirillgroshkov did you ever manage to fix the issue that you get after installing import-export?
Getting the same thing about the unexpected string regarding:
/node_modules/@angular/compiler/bundles/compiler.umd.js:19810
("ort * as " + prefix + " = require("" + importedModuleName + "");"));
Interestingly, this is the code that it's complaining about:
converter.importsWithPrefixes.forEach(function (prefix, importedModuleName) {
// Note: can't write the real word for import as it screws up system.js auto detection...
preambleLines.push("imp" +
("ort * as " + prefix + " from '" + importedModuleName + "';"));
});
same issue with ng-cookies.
hello ,i followed your advice ,but not working @harshes53
externals: [nodeExternals({whitelist: [/ngx-cookie/]})],
Is there any resolution on this issue yet? Or an ETA? Neither the require('import-export') or the webpack workarounds suggested above have worked for me; the first throws errors when using the @ng-bootstrap datepicker module (Unexpected token export from the npm), and the second throws various @NgModule annotation errors that I can't seem to work around at all (I've played whack-a-mole with them for hours now).
We really need a way to bundle all node_modules for server-side rendering.
https://medium.com/@cyrilletuzi/angular-server-side-rendering-in-node-with-express-universal-engine-dce21933ddce
@intellix No, I gave up on SSR with angular. Went with prerendering approach (instead of SSR), used Puppeteer to go through all URLs, render the page, save resulting html file, then served html files as static. Drawback is that prerendering is significantly slower (even in multi-threaded environment).
For future project I'll consider a framework (not Angular) that has SSR fixed (e.g React/Next.js, or stenciljs, or VueJS).