angular-google-maps: Angular 4 Universal - SyntaxError: Unexpected token export
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
- Clone project https://github.com/philippeboyd/angular-seo
- npm install
- npm run start
Current behavior Compiles but server cannot start
$ npm run start
> ang4-seo@0.0.0 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]
> ang4-seo@0.0.0 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! ang4-seo@0.0.0 start: `ts-node src/server.ts`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ang4-seo@0.0.0 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…
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 18
- Comments: 76
Commits related to this issue
- fix: SyntaxError: Unexpected token import https://github.com/SebastianM/angular-google-maps/issues/1052#issuecomment-331150772 — committed to cj-wang/mean-start-2 by cj-wang 5 years ago
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):
npm install --save-dev @babel/core @babel/cli @babel/preset-env
add this to the root project under the name
.babelrc
or add the presets directly via cli{ "presets": ["@babel/preset-env"] }
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",
add a postinstall script in package.json in “scrtipsts” scope
"postinstall": "npm run compile_@agm_core",
run
npm i
to install the deps. After installing the deps, the script postinstall will run and babel will compile the targeted js filesrun your server and should world
Give me please feedback if it works. I did the same thins for more than 3 npm modules it works on my machine 😄
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 (withSyntaxError: 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 modulesThe fix is to use
angularCompilerOptions
’sflatModuleOutFile
&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 themodule
andtypings
entry points. Since those options require a unique entry point per library, I had to split the maintsconfig.json
files in order to supportjs-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 loaderload()
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.
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…
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.
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
andexport
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
andexport
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 😃
Finally able to use google map with universal. I am making repo and video
@AnthonyNahas
Your are a god my friend …
@AnthonyNahas honestly thanks for your solution, it’s working for me with latest version babel and angular 6.
@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:
@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 🍻
@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 withjest
. 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:
cd node_modules
cd \@agm/core
package.json
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 👍 ❤️
@AnthonyNahas. This is also working for me. Thanks
externals: [nodeExternals({ whitelist: [ /^@agm\/core/, ] })],
did the job for me. Thank you. Otherwise @AnthonyNahas solution should do the job.@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 this worked for me, i dont know how you came up with that solution but thank you,
@karthikeyanmanureva u should do the same thing for antoher npm module which is throwing “SyntaxError: Unexpected token import” … @martinreus cheers
@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?
My webpack.config.js https://gist.github.com/kkaabbaa/a308b218938ae55357f73c162e887bd5
Use webpack.config
@AnthonyNahas
Thanks a lot, it’s still work on Angular 7
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).
@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.
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 , 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!
@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!!
@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 MVP
@AnthonyNahas thanks so much
@AnthonyNahas , thanks, for one module it worked. But now I’m using another package ng2-slim-loading-bar and it throws error:
Any idea how can I fix it?
@AnthonyNahas ,your solution has helped me solve this problem
@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 =)
@AnthonyNahas that is a very interesting idea. It seems too good to be true! I’ll give it a go
I used this post https://medium.com/@evertonrobertoauler/angular-4-universal-app-with-angular-cli-db8b53bba07d
and added