Error "Unexpected token import" when trying to run Angular Universal

Viewed 1229

I am trying to produce an Angular Universal, but I came across an issue with "ts-node server.ts". Output logged below:

$ npm run start

> prestart public-site
> ng build --prod && ngc

 12% building modules 24/32 modules 8 active ...lic-site/src/styles.scssNode#moveTo was deprecated. Use Container#append.
Hash:                                                               
Time: 76999ms
chunk    {0} 0.chunk.js 11.9 kB {1} {2} {3} {4} {5} {6} 
chunk   {14} inline.bundle.js (inline) 0 bytes

> start public-site
> ts-node src/server.ts

public-site/node_modules/md2/module.js:7
import { NgModule } 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.<anonymous> (public-site/src/app/app.module.ts:11:1)

npm ERR! Darwin 16.5.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "start"
npm ERR! node v7.10.0
npm ERR! npm  v4.2.0
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! start: `ts-node src/server.ts`
npm ERR! Exit status 1
npm ERR! 

If you have any idea how to fix this, it would be greatly appreciated.

2 Answers

Just a note for people visiting this in the future (like I did) that hammerjs and jquery will cause problems, hammerjs is part of the popular Material 2 lib so its a common issue for people making this transition.

Worst comes to worst you can take out third party libs and re-add them one by one and launch the server each time to see if it works.

You can also limit when something is called to when it renders in browser like so;

import { PLATFORM_ID } from '@angular/core';
 import { isPlatformBrowser, isPlatformServer } from '@angular/common';

 constructor(@Inject(PLATFORM_ID) private platformId: Object) { ... }

 ngOnInit() {
   if (isPlatformBrowser(this.platformId)) {
      // Client only code.
      ...
   }
   if (isPlatformServer(this.platformId)) {
     // Server only code.
     ...
   }
 }

- Extract from universal-starter found here: https://github.com/angular/universal-starter

So if you need to use jquery, make sure any call you make is within 'isPlatformBrowser', because jquery and other similar libs play with the DOM and the DOM doesnt exist in the node backend, thus causing errors.

Related