Angular-google-maps: Angular 4 Universal - SyntaxError: Unexpected token export

Created on 21 Jun 2017  ·  76Comments  ·  Source: SebastianM/angular-google-maps

Issue description
I'm unable to start my project in universal mode. However, when executing it in AOT with ng serve, all is well.

Steps to reproduce and a minimal demo of the problem

  1. Clone project https://github.com/philippeboyd/angular-seo
  2. npm install
  3. npm run start

Current behavior
Compiles but server cannot start

$ npm run start

> [email protected] prestart /home/philippe/web/angular-seo
> ng build --prod && ngc

Hash: 7d85520031346575c3db                                                              
Time: 24216ms
chunk    {0} polyfills.fdc74e8f101f8a37cfda.bundle.js (polyfills) 160 kB {4} [initial] [rendered]
chunk    {1} main.1765992e8c1c2054a14a.bundle.js (main) 30.1 kB {3} [initial] [rendered]
chunk    {2} styles.d41d8cd98f00b204e980.bundle.css (styles) 69 bytes {4} [initial] [rendered]
chunk    {3} vendor.54e8d36ccd5e25bbf525.bundle.js (vendor) 1.52 MB [initial] [rendered]
chunk    {4} inline.9e599a3566ef53034f50.bundle.js (inline) 0 bytes [entry] [rendered]

> [email protected] start /home/philippe/web/angular-seo
> ts-node src/server.ts

/home/philippe/web/angular-seo/node_modules/@agm/core/index.js:2
export * from './directives';
^^^^^^
SyntaxError: Unexpected token export
    at Object.exports.runInThisContext (vm.js:73:16)
    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> (/home/philippe/web/angular-seo/src/app/app.module.ts:5:1)
    at Module._compile (module.js:571:32)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `ts-node src/server.ts`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Expected/desired behavior
Server starting without errors

angular2 & angular-google-maps version

  • Angular 4.1.3
  • agm/core 1.0.0-beta.0

Other information
I've looked into issue #668 but it's doesn't seem to be the same issue...

important stale bug

Most helpful comment

_Updated the solution to the latest version of babel_

@philippeboyd @dkmostafa i solved the same issue recently for this module and others like --> ngx translate and more...

solution (compile the js files into es2015):

  1. npm install --save-dev @babel/core @babel/cli @babel/preset-env
  2. add this to the root project under the name .babelrc or add the presets directly via cli
    { "presets": ["@babel/preset-env"] }
  3. add a npm script in package.json in "scrtipsts" scope
    "compile_@agm_core": "babel node_modules/@agm/core -d node_modules/@agm/core --presets @babel/preset-env",

  4. add a postinstall script in package.json in "scrtipsts" scope
    "postinstall": "npm run compile_@agm_core",

  5. run npm i to install the deps. After installing the deps, the script postinstall will run and babel will compile the targeted js files

  6. run your server and should world

  7. Give me please feedback if it works. I did the same thins for more than 3 npm modules it works on my machine :D

All 76 comments

Hello, I've had to deal with this issue which is not really an Agm issue but a global one.
Most of the recent packages, including Agm are compoiled in es6, with import and export keywords.

This was not an issue before Universal since there is always a bundle file in the packages for lets say System.js for local dev and Webpack/Rollup will understand es6 for production bundles.

But with Universal, you directly use the files in the node_modules, in es6 then, and node do not know about import and export tokens yet.

Two things can be done, you can bundle your app even for universal, but you will lose a lot of compile time juste for a bundle that is useless in a server context.

Other option, the one I used in my company, is to copy all your sources in a tmp folder before compile and create a node_modules folder in this tmp folder.
You can then copy all the @agm folder (the one in the "real" node_module folder in the "fake" one in tmp. You will then be able to use babel to transform the es6 files copied in the fake node_modules folder in commonjs that nodejs will understand. (when you require @agm node will look for the file in the fake node_modules folder)

This is super annoying and there is not really other options for now (let me know if you find a better one). I really think ng2 modules have to find a way to provide both es6 and commonjs files if they want their modules to be easy to use with universal :)

Use webpack.config

externals: [nodeExternals({
    whitelist: [
      /^@agm\/core/,
    ]
})],

@kkaabbaa can you confirm that this works?
Simply adding it to my webpack didn't get the job done.

i have the same problem, i have babel and i did make a copy of the project in a new folder then a have babel locally installed but i would like to understand the process that Adrienboulle he mades for his company because i have to get finis this thing thank you in advance.

i have add it to webpack.config and it dosen`t work for me.

externals: [nodeExternals({
whitelist: [
/^@agm/core/,
]
})],

I have it working with a workaround by dynamically loading a component that contains my agm-map based on if it's the browser or server: https://angular.io/guide/dynamic-component-loader

I have compiled to es5 but also showing error

Finally able to use google map with universal. I am making repo and video

I used this post https://medium.com/@evertonrobertoauler/angular-4-universal-app-with-angular-cli-db8b53bba07d

and added

externals: [nodeExternals({
    whitelist: [
      /^@agm\/core/,
    ]
})],

@kkaabbaa where did you add, please?

Still not working , i tried @kkaabbaa solution , but didnot worked for me , same issue

_Updated the solution to the latest version of babel_

@philippeboyd @dkmostafa i solved the same issue recently for this module and others like --> ngx translate and more...

solution (compile the js files into es2015):

  1. npm install --save-dev @babel/core @babel/cli @babel/preset-env
  2. add this to the root project under the name .babelrc or add the presets directly via cli
    { "presets": ["@babel/preset-env"] }
  3. add a npm script in package.json in "scrtipsts" scope
    "compile_@agm_core": "babel node_modules/@agm/core -d node_modules/@agm/core --presets @babel/preset-env",

  4. add a postinstall script in package.json in "scrtipsts" scope
    "postinstall": "npm run compile_@agm_core",

  5. run npm i to install the deps. After installing the deps, the script postinstall will run and babel will compile the targeted js files

  6. run your server and should world

  7. Give me please feedback if it works. I did the same thins for more than 3 npm modules it works on my machine :D

@AnthonyNahas that is a very interesting idea. It seems too good to be true! I'll give it a go

Anyone have a solution for this? Just recently encountered this as well.

@adrienboulle thanks for explaining things, now I wonder: would it not be better to release the package in a different format that is also suitable for Angular Universal? That way all the workarounds circulating here would no longer be needed. Or would it be possible to make Angular Universal understand ES6 code?

@AnthonyNahas I tried that. Now it shows another error

import * as i0 from '@angular/core';
^^^^^^
SyntaxError: Unexpected token import

@AnthonyNahas, thank you so much for your solution! I tried several other solutions that didn't work for me for roughly one month! This actually solves my problem =)

@karthikeyanmanureva u should do the same thing for antoher npm module which is throwing "SyntaxError: Unexpected token import" ...
@martinreus cheers

@AnthonyNahas this worked for me, i dont know how you came up with that solution but thank you,

@AnthonyNahas ,your solution has helped me solve this problem

@AnthonyNahas , thanks, for one module it worked. But now I'm using another package ng2-slim-loading-bar and it throws error:

some_path/client/dist/ngfactory/node_modules/ng2-slim-loading-bar/style.css.shim.ngstyle.ts:9

export const styles:any[] = ['.slim-loading-bar[_ngcontent-%COMP%] {\n    position: fixed;\n    margin: 0;\n    padding: 0;\n    top: 0;\n    left: 0;\n    right: 0;\n    z-index: 99999;\n}\n\n\n.slim-loading-bar-progress[_ngcontent-%COMP%] {\n    margin: 0;\n    padding: 0;\n    z-index: 99998;\n    background-color: green;\n    color: green;\n    box-shadow: 0 0 10px 0; \n    height: 2px;\n    opacity: 0;\n\n    \n    -webkit-transition: all 0.5s ease-in-out;\n    -moz-transition: all 0.5s ease-in-out;\n    -o-transition: all 0.5s ease-in-out;\n    transition: all 0.5s ease-in-out;\n}'];
^^^^^^

SyntaxError: Unexpected token export

Any idea how can I fix it?

add it to the exclude section and the webpack at least try it to see if it
works

2017-11-20 15:18 GMT+01:00 lomboboo notifications@github.com:

@AnthonyNahas https://github.com/anthonynahas , thanks, for one module
it worked. But now I'm using another package ng2-slim-loading-bar
https://github.com/akserg/ng2-slim-loading-bar and it throws error:

some_path/client/dist/ngfactory/node_modules/ng2-slim-loading-bar/style.css.shim.ngstyle.ts:9

export const styles:any[] = ['.slim-loading-bar[_ngcontent-%COMP%] {\n position: fixed;\n margin: 0;\n padding: 0;\n top: 0;\n left: 0;\n right: 0;\n z-index: 99999;\n}\n\n\n.slim-loading-bar-progress[_ngcontent-%COMP%] {\n margin: 0;\n padding: 0;\n z-index: 99998;\n background-color: green;\n color: green;\n box-shadow: 0 0 10px 0; \n height: 2px;\n opacity: 0;\n\n \n -webkit-transition: all 0.5s ease-in-out;\n -moz-transition: all 0.5s ease-in-out;\n -o-transition: all 0.5s ease-in-out;\n transition: all 0.5s ease-in-out;\n}'];
^^^^^^

SyntaxError: Unexpected token export

Any idea how can I fix it?


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/SebastianM/angular-google-maps/issues/1052#issuecomment-345708386,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AQFpli_Y29p1Fd66V0COJ32nX1LbECVpks5s4Yo7gaJpZM4OAQmB
.

@lomboboo add a new npm script to transpile the ng2-slim... module
--> add a npm script in package.json in "scrtipsts" scope
"compile_ng2-slim-loading-bar": "babel node_modules/ng2-slim-loading-bar -d node_modules/ng2-slim-loading-bar --presets es2015",

then -->

add a postinstall script in package.json in "scrtipsts" scope "postinstall": "npm run compile_@agm_core && npm run compile_ng2-slim-loading-bar ",

--> after that run npm i one more time

--> result
the other module should be transpiled too

@AnthonyNahas thanks so much

@AnthonyNahas , as I mentioned I already have script that transpiles this module to 2015. I have a bit different way, but idea the same. So I have:

    "ng2_slim:tocommonjs": "node node_modules/babel-cli/bin/babel.js node_modules/ng2-slim-loading-bar/src -d --out-dir node_modules/ng2-slim-loading-bar/src --presets es2015",
    "prestart": "npm run ng2_slim:tocommonjs && npm run ngxerrors:tocommonjs && ng build --prod && ngc",
    "start": "ts-node src/server.ts"

Or it matters to do exactly your way, during postinstall hook?

@AnthonyNahas , I've tried compile to 2015 during postinstall hook, but error appears anyway. I think that client/dist/ngfactory/node_modules/ng2-slim-loading-bar/style.css.shim.ngstyle file generated by Angular, but I have no idea how to make it work.

@lomboboo

on postinstall it's not important!

Is that block the same one that u used in your project ?

I found a bug in the first npm script: u may need to transpile other files than theses files in the src -->

before -->
"ng2_slim:tocommonjs": "node node_modules/babel-cli/bin/babel.js node_modules/ng2-slim-loading-bar/src -d --out-dir node_modules/ng2-slim-loading-bar/src --presets es2015",

should be (after) -->

"ng2_slim:tocommonjs": "babel node_modules/ng2-slim-loading-bar -d --out-dir node_modules/ng2-slim-loading-bar --presets es2015",

PS: if you run a npm script from the terminal u can use babelinstead of node_modules/babel-cli/bin/babel.js. The other one is only helpful when your running your tasks immediately from the terminal and not via npm...

I have just forked this repo and i will provide soon a better solution to solve this kind of errors, like unexpected token export/import ... so that the developer can uses this module without transpile manually the src files and run a custom npm script..

@AnthonyNahas MVP

@AnthonyNahas , so I ended up with this solution. I created webpack.config.js, which is for server and configure it like this:

const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
  entry: {
    server: './src/server.ts'
  },
  resolve: {
    extensions: ['.ts', '.js'],
    alias: {
      'main.server': path.join(__dirname, 'dist', 'server', 'main.bundle.js')
    }
  },
  target: 'node',
  plugins: [
    //new webpack.NormalModuleReplacementPlugin(/\.\.\/environments\/environment/, '../environments/environment.prod')
  ],
  externals: [nodeExternals({
    whitelist: [
      /^ng2-slim-loading-bar/,
    ]
  })],
  node: {
    __dirname: false,
    __filename: false
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js'
  },
  module: {
    rules: [
      { test: /\.ts$/, loader: 'ts-loader' }
    ]
  }
};

So you need to install webpack and webpack-node-externals locally. Inside nodeExternals you can define plugins,packages which you don't need when server compiles. In my case it is ng2-slim-loading-bar plugin that throws error I described.
And finally just add webpack to package.json when you running server script. My package.json looks like this:

...
"prestart": "ng build --prod && ngc && webpack",
 "start": "node dist/server.js",
...

If you have not standard name of webpack.config.js than you need to specify correct name as webpack argument. For example,

...
"prestart": "ng build --prod && ngc && webpack --config webpack.server.config.js", // <<<-------
 "start": "node dist/server.js",
...

I hope it will help somebody. In my opinion it is more robust solution that compiling every plugin your server have problem with.

@AnthonyNahas i am facing the same issue and tried your solution but
What to do for below point you given in the solution

  • add this to the root project under the name .babelrc
    { "presets": ["es2015"] }

@Harshketu
in your project, at the top level (root) --> create a file with the name .babelrc and paste
the following --> { "presets": ["es2015"] } <-- in that file

@AnthonyNahas
is your solution working with webpack.config file or without?

it depends whether your project is ejected.
However, transpiling the code into es5 has not a direct dependency to the webpack.config file

Following @AnthonyNahas his solution, I pushed a compiled version to git so one can directly use it in package.json without having to install babel etc:

"@agm/core": "git+https://github.com/cmddavid/core.git"

Might be of use to anyone. I'm using Firebase Hosting, and for some reason Firebase doesn't seem to be compiling the code even though I'm using exactly the same method as described by Anthony on the package.json for Firebase. So thats why I use this workaround.

@cmddavid I ran into this issue on firebase as well. It won't work on firebase because it installs node modules again and doesn't have babel-cli installed globally.

@dockleryxk so does this mean my solution is the only workable solution when using Firebase?

I dont fully understand why Firebase is installing all the modules again. Isn't the server bundle that is being generated on the client before deployment enough? As far as I can tell the node script being executed by the Firebase Function only requires a very limited set of node packages. Certainly not the @agm/core package. Since the server bundle is already being sent to the server during deployment.

@cmddavid It could potentially take a long time to upload a node modules directory would be my guess as to why, but I don't actually know. Personally, I put the compiled modules in a directory inside the functions directory and just reference it from the package.json in the functions directory. For example "@agm/core": "file:./compiled_modules/@agm/core"

@AnthonyNahas saved my day. Was struggling to get this Angular Universal Server Side rendering up and running for weeks now. Your solution worked like a charm!!

@AnthonyNahas , Thankyou so much , working fine for me , when I have opened the @agm files , after seeing ES6 syntax, first thought went for compiling using webpack which is a tought one(atleast for me), anyway thanks again, have setup Angular Universl SSR and absolutely fine now!

externals: [nodeExternals({ whitelist: [ /^@agm\/core/, ] })], did the job for me. Thank you. Otherwise @AnthonyNahas solution should do the job.

I had the same problem with one of my own packages, and it turned out making the package "Angular Package Format" compatible did the trick. This is a very useful npm package to help with that: https://github.com/dherges/ng-packagr

Its pretty much plug and play.

@AnthonyNahas. This is also working for me.
Thanks

Do you guys still have problems with this? I'm using this module in a Universal project and it's all working file out of the box. What versions are you using?

Hi @AnthonyNahas, I can't seem to get this to work for ng2-google-place-autocomplete

I get this error message:
`C:\Users\Andrenode_modules\ng2-google-place-autocompleteindex.ts:6
export * from './src/index';
^^^^^^

SyntaxError: Unexpected token export
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:599:28)
at Module._extensions..js (module.js:646:10)
at Object.require.extensions.(anonymous function) [as .ts] (C:\Users\Andrenode_modulests-node\srcindex.ts:392:14)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)`

I then followed your steps:

  1. npm i --save -dev babel-cli babel-preset-es2015

  2. add this to the root project under the name .babelrc
    { "presets": ["es2015"] }

  3. add this script to my package.json file

"scripts": {
"compile_ng2-google-place-autocomplete": "babel node_modules/ng2-google-place-autocomplete -d node_modules/ng2-google-place-autocomplete --presets es2015",
"prestart": "ng build --prod && ngc",
"start": "ts-node src/server.ts",
"postinstall": "npm run compile_ng2-google-place-autocomplete"
}

  1. run npm i to install the deps. After installing the deps, the script postinstall will run and babel will compile the targeted js files

  2. Run npm run start

  3. I still get the error the same error.

If you could help me that would be really great help as I have spent hours trying to fix this!

@dockleryxk, @AnthonyNahas, @cmddavid is a simpler, and easier way...
yarn add agm-compiled. Without webpack and sytemjs nonsens, work angular5^ + universal + ssr + firebase hosting/functions.

@retrwood that's great, would be nice to have a NPM version available too though.

Thanks @AnthonyNahas ,
You saved my day, its really great work around, as i wasn't agree with ejecting cli tool.

Thank you so much.

@AnthonyNahas babel-preset-es2015 is deprecated now. How can we handle this issue ?

@Gomathipriya thanks for asking! You gave me the motivation to finally send a pull request!

21.9.2017, I published a solution to handle this bug! At that time, I didn't know that the library is generating the write code like bundle, es5... I had too many projects and I was not able to find what's going really wrong with @agm/core ! Well, yesterday I was developing an angular material extensions for angular apps that are using @agm/core and I faced the same issue while tesing with jest. So I decided to take a further look to this project and I found something interesting.

Actually, we don't need anymore to transpile the code to es5 since the build of this project did that already for us. But typescript don't know about them! Some information are missed in the package.json.

So tipp to solve that:

  1. go to cd node_modules
  2. cd \@agm/core
  3. open the package.json
  4. and add the following
 "main": "core.umd.js",
  "es2015": "index.js",
  "typings": "index.d.ts",

and the bug should be solved! Now when compiling, typescript will pick the right js code!

I sent few seconds ago a pull request!

Please support this PR after testing that on your machine!

I test it the following scenario here in this project @angular-material-extensions/google-maps-autocomplete

if you like project, please support me by starring and share it!

Thank you all 👍 ❤️

Any news ? @SebastianM

@AnthonyNahas we're seeing this same issue with the map clusterer package as well. Super frustrating, I appreciate your taking the time to work on it. Is there a proposed solution that I could implement while the PR is in review?

I can add this manually to make our tests pass, but it will still fail in the pipeline.

@Gomathipriya I've just updated the above posted solution to the latest version of babel v7.1.0, and I tested the process in my own npm mobule @angular-material-extensions/google-maps-autocomplete

check circleci status here

travis-ci status here

@mcblum you should probably the same thing like the core module (see the above posted solution)

cheers 🍻

Agm is really awesome and handy but unfortunately I wasn't able to help regarding the PR, probably too complicated for me.

So I decided to implement a custom code for the Google Maps Javascript API which turned into a new Web Component called web-google-maps which I published today and used as a replacement in my project in order to solve the issue.

Again, Agm is awesome and this Web Component doesn't offer so much possibilities as this library does. I just thought I would write these lines and mention it in case someone who's facing the problem would be on a rush to find a potential solution, nothing else nothing more.

I don't have any issue while building but when requesting a page which is supposed to be server side rendered I get the following error:

ERROR { ReferenceError: window is not defined
    at WindowRef.getNativeWindow (webpack:///./node_modules/@agm/core/utils/browser-globals.js?:8:57)
    at LazyMapsAPILoader.load (webpack:///./node_modules/@agm/core/services/maps-api-loader/lazy-maps-api-loader.js?:45:38)
    at new FitBoundsService (webpack:///./node_modules/@agm/core/services/fit-bounds.js?:38:81)
    at createClass (webpack:///./node_modules/@angular/core/fesm5/core.js?:19057:20)
    at _createProviderInstance$1 (webpack:///./node_modules/@angular/core/fesm5/core.js?:19042:20)
    at createProviderInstance (webpack:///./node_modules/@angular/core/fesm5/core.js?:18919:12)
    at createViewNodes (webpack:///./node_modules/@angular/core/fesm5/core.js?:20149:36)
    at Object.createEmbeddedView (webpack:///./node_modules/@angular/core/fesm5/core.js?:20070:5)
    at TemplateRef_.createEmbeddedView (webpack:///./node_modules/@angular/core/fesm5/core.js?:18651:38)
    at ViewContainerRef_.createEmbeddedView (webpack:///./node_modules/@angular/core/fesm5/core.js?:18517:35)
    at NgIf._updateView (webpack:///./node_modules/@angular/common/fesm5/common.js?:3489:45)
    at NgIf.set [as ngIf] (webpack:///./node_modules/@angular/common/fesm5/common.js?:3457:18)
    at updateProp (webpack:///./node_modules/@angular/core/fesm5/core.js?:19212:37)
    at checkAndUpdateDirectiveInline (webpack:///./node_modules/@angular/core/fesm5/core.js?:18963:19)
    at checkAndUpdateNodeInline (webpack:///./node_modules/@angular/core/fesm5/core.js?:20270:20)
    at checkAndUpdateNode (webpack:///./node_modules/@angular/core/fesm5/core.js?:20232:16)
    at prodCheckAndUpdateNode (webpack:///./node_modules/@angular/core/fesm5/core.js?:20773:5)
    at Object.eval [as updateDirectives] (webpack:///./dist/server/main.js?:45103:316)
    at Object.updateDirectives (webpack:///./node_modules/@angular/core/fesm5/core.js?:20561:72)
    at checkAndUpdateView (webpack:///./node_modules/@angular/core/fesm5/core.js?:20214:14)
    at callViewAction (webpack:///./node_modules/@angular/core/fesm5/core.js?:20455:21)
    at execComponentViewsAction (webpack:///./node_modules/@angular/core/fesm5/core.js?:20397:13)
    at checkAndUpdateView (webpack:///./node_modules/@angular/core/fesm5/core.js?:20220:5)
    at callViewAction (webpack:///./node_modules/@angular/core/fesm5/core.js?:20455:21)
    at execComponentViewsAction (webpack:///./node_modules/@angular/core/fesm5/core.js?:20397:13)
    at checkAndUpdateView (webpack:///./node_modules/@angular/core/fesm5/core.js?:20220:5)
    at callViewAction (webpack:///./node_modules/@angular/core/fesm5/core.js?:20455:21)
    at execEmbeddedViewsAction (webpack:///./node_modules/@angular/core/fesm5/core.js?:20418:17)
    at checkAndUpdateView (webpack:///./node_modules/@angular/core/fesm5/core.js?:20215:5)
    at callViewAction (webpack:///./node_modules/@angular/core/fesm5/core.js?:20455:21)
    at execComponentViewsAction (webpack:///./node_modules/@angular/core/fesm5/core.js?:20397:13)
    at checkAndUpdateView (webpack:///./node_modules/@angular/core/fesm5/core.js?:20220:5)
    at callViewAction (webpack:///./node_modules/@angular/core/fesm5/core.js?:20455:21)
    at execEmbeddedViewsAction (webpack:///./node_modules/@angular/core/fesm5/core.js?:20418:17)
    at checkAndUpdateView (webpack:///./node_modules/@angular/core/fesm5/core.js?:20215:5)
    at callViewAction (webpack:///./node_modules/@angular/core/fesm5/core.js?:20455:21)
    at execComponentViewsAction (webpack:///./node_modules/@angular/core/fesm5/core.js?:20397:13)
    at Object.checkAndUpdateView (webpack:///./node_modules/@angular/core/fesm5/core.js?:20220:5)
    at ViewRef_.detectChanges (webpack:///./node_modules/@angular/core/fesm5/core.js?:18595:22)
    at eval (webpack:///./node_modules/@angular/core/fesm5/core.js?:15257:63)
    at Array.forEach (<anonymous>)
    at ApplicationRef.tick (webpack:///./node_modules/@angular/core/fesm5/core.js?:15257:25)
    at eval (webpack:///./node_modules/@angular/core/fesm5/core.js?:15148:105)
    at ZoneDelegate.invoke (webpack:///./node_modules/zone.js/dist/zone-node.js?:387:26)
    at Object.onInvoke (webpack:///./node_modules/@angular/core/fesm5/core.js?:14529:33)
    at ZoneDelegate.invoke (webpack:///./node_modules/zone.js/dist/zone-node.js?:386:32)
    at Zone.run (webpack:///./node_modules/zone.js/dist/zone-node.js?:137:43)
    at NgZone.run (webpack:///./node_modules/@angular/core/fesm5/core.js?:14443:28)
    at Object.next (webpack:///./node_modules/@angular/core/fesm5/core.js?:15148:81)
    at SafeSubscriber.schedulerFn [as _next] (webpack:///./node_modules/@angular/core/fesm5/core.js?:10544:52)

@maxime1992 maybe try a quick fix: display your map only on the browser side, there isn't any window element on the server side (that's why it could be built but it fails at runtime)

pseudo code:

<ng-container *ngIf="isPlatformBrowser(platformId)">
  <here-your-agm-map/>
</ng-container>

@AnthonyNahas i tried your solution but still got same error.
i am trying to deploy my server bundle at cloud fire function...

without agm everything is ok/working but with agm got error--

functions[ssr(us-central1)]: Deployment error.
Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /user_code/node_modules/@agm/core/services/managers/circle-manager.js:1
(function (exports, require, module, __filename, __dirname)
{ import { Injectable, NgZone } 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:549:28)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at Object.@agm/core/services/managers/circle-manager (/user_code/dist/server/main.js:4999:18)

please reply

That means the babel compiler didn't do its job as it would have replaced the imports. Both repos should be available pre compiled in my github. You may use that if you are unable to do the babel part.

@AnthonyNahas honestly thanks for your solution, it's working for me with latest version babel and angular 6.

@AnthonyNahas

Your are a god my friend ...

There is multiple issues preventing that package from being used on the server-side through Angular Universal. I've already did similar work on various libraries (e.g. https://github.com/salemdar/ngx-cookie/pull/41, https://github.com/zefoy/ngx-perfect-scrollbar/pull/129, https://github.com/mattlewis92/angular-resizable-element/pull/80), so I thought I'd have a look.

In short, when targeting the server platform with the Angular CLI only the app itself is compiled, as the library UMD bundle would then be used when running it in NodeJS. As pointed out by @AnthonyNahas, this means that the main package entry point must point to said UMD bundle, i.e. something NodeJS natively understands.

In addition to the NodeJS-native UMD bundle, best practices for libraries as per the Angular Package Format guidelines is to also publish AoT-friendly ES modules and metadata.json metadata files, which that package already does. However, due to https://github.com/angular/angular-cli/issues/7200, the Angular Universal build currently fail (with SyntaxError: Unexpected token export-like errors) when said library is published as separate ES modules instead of a flatten one (fesm), as the deep imports would then resolved to the ES modules causing Node to fail as it doesn't understand ES modules

The fix is to use angularCompilerOptions's flatModuleOutFile & flatModuleId params, as per https://angular.io/guide/aot-compiler, and pass the output through Rollup, in order to produce flat ES module & typings files, and then set those as the module and typings entry points. Since those options require a unique entry point per library, I had to split the main tsconfig.json files in order to support js-marker-clusterer & snazzy-info-window.

In addition, the rollup configs were setting context: 'window', which breaks on the server-side, which I switched back to Rollup's default "this as undefined" behavior (which albeit being a warning, is actually the expected behavior).

Last, now that your app universal build compiles with this library, you need to decide what to do at runtime / make the code itself Universal friendly, which I achieved using isPlatformBrowser(this.platformId) in the Google Maps SDK loader load() function to just skip the injection. It does the trick for our current use case, but most safeguards could be needed in order to disable that library on the server side (since the Google Maps SDK won't run there anyway).

Anyway, the PR is at https://github.com/SebastianM/angular-google-maps/pull/1554, comments welcome. I have a fork running at @laurentgoudet/agm-core which I'm successfully using for my project (until this PR gets merged). I'm using the Angular CLI but it should work with any builder - feedback welcome.

After a lot of tries, the solution provided by @AnthonyNahas allowed me to deploy a universal app as a firebase function :) .
My suggestion is to check if the ts files are effectively transformed into js, if they are, then the error about import/export must not appear.

Edit (26/12/2018)
I run to the problem again with the snazzy info window module. I ended up discovering that babel was not running when I was using firebase deploy (Remember that when deploying AU as a firebase function, a npm install is performed, which means that the package will install again as ts files). In the end, I just forked the library(https://github.com/jota12x/angular-google-maps), apply babel, and install it from the repo. Problem solved. (Waiting for the fix in the main repo though).

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Any activity on this? It is quite simple to fix - just need to start using @angular-devkit/build-angular. This is one of most serious problems because people have 2 ways out:
1) Use custom webpack configs
2) Use some hacks

and starting use @angular-devkit/build-angular is quite simple and could save hours of hacking

@AnthonyNahas

_Updated the solution to the latest version of babel_

@philippeboyd @dkmostafa i solved the same issue recently for this module and others like --> ngx translate and more...

solution (compile the js files into es2015):

  1. npm install --save-dev @babel/core @babel/cli @babel/preset-env
  2. add this to the root project under the name .babelrc or add the presets directly via cli
    { "presets": ["@babel/preset-env"] }
  3. add a npm script in package.json in "scrtipsts" scope
    "compile_@agm_core": "babel node_modules/@agm/core -d node_modules/@agm/core --presets @babel/preset-env",
  4. add a postinstall script in package.json in "scrtipsts" scope
    "postinstall": "npm run compile_@agm_core",
  5. run npm i to install the deps. After installing the deps, the script postinstall will run and babel will compile the targeted js files
  6. run your server and should world
  7. Give me please feedback if it works. I did the same thins for more than 3 npm modules it works on my machine :D

Thanks a lot, it's still work on Angular 7

Buts thats a hack... Or workaround...

On Tue, Apr 2, 2019, 12:53 PM PEA notifications@github.com wrote:

@AnthonyNahas https://github.com/AnthonyNahas

Updated the solution to the latest version of babel

@philippeboyd https://github.com/philippeboyd @dkmostafa
https://github.com/dkmostafa i solved the same issue recently for this
module and others like --> ngx translate and more...

solution (compile the js files into es2015):

  1. npm install --save-dev @babel/core @babel/cli @babel/preset-env
  2. add this to the root project under the name .babelrc or add the
    presets directly via cli
    { "presets": ["@babel/preset-env"] }
  3. add a npm script in package.json in "scrtipsts" scope
    "compile_@agm_core": "babel node_modules/@agm/core -d
    node_modules/@agm/core --presets @babel/preset-env",
  4. add a postinstall script in package.json in "scrtipsts" scope
    "postinstall": "npm run compile_@agm_core",
  5. run npm i to install the deps. After installing the deps, the
    script postinstall will run and babel will compile the targeted js files
  6. run your server and should world
  7. Give me please feedback if it works. I did the same thins for more
    than 3 npm modules it works on my machine :D

Thanks a lot, it's still work on Angular 7


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/SebastianM/angular-google-maps/issues/1052#issuecomment-478944955,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ADvMl79FA7YGEZN_DSvwaOsUS7zXFW9Rks5vczbEgaJpZM4OAQmB
.

I've used the solution of @AnthonyNahas but I'm getting this error:

/node_modules/@agm/core/services/maps-api-loader/maps-api-loader.js:44
        type: _core.Injectable
                    ^

TypeError: Cannot read property 'Injectable' of undefined

@HighSoftWare96 the problem is not related directly to the library... it seems to be a compile error...

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

We are going to move to ngc soon, so hopefully it will work with Angular Universal. Personally, I have 0 experience and knowledge in universal, and AoT.

Ok, I pulled in ng-packagr PR, so maybe now it will work. Can you try forking master and seeing if it works?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Hi @doom777
Can you please tell me, when you are planning to release this merge? I would love to drop my patched version of this library :)

Not up to me

Was this page helpful?
0 / 5 - 0 ratings