desandro / masonry

:love_hotel: Cascading grid layout plugin
https://masonry.desandro.com
16.28k stars 2.11k forks source link

Ensuring that masonry will only be initialized on the client side (SSR fix) #1121

Open cliqqz opened 4 years ago

cliqqz commented 4 years ago

Since JS frameworks / libraries + SSR (Server-Server-Rendering) got pretty popular it would be great to make this plugin work with SSR projects. This condition ensures that the masonry plugin will only load within the browser and not on the server and eventually crash it by resulting in a ReferenceError for the window object.

an older reference issue I found where other people experienced this: https://github.com/desandro/masonry/issues/966

desandro commented 3 years ago

Thanks for this contribution. I think there is a better solution to load import masory-layout when you're in a SSR environment.

drewbaker commented 9 months ago

I would Masonry to have not throw window not defined errors when used with import. Yes you can work around this with a require() but now with the popularity of Vite that doesn't work out of the box either. So this PR would have been a nice solution I think.

Xyaren commented 9 months ago

This is also blocking me from using SSR. Please consider this PR.

jvyden commented 9 months ago

For those looking for a workaround for Angular SSR while this PR becomes official, you can tell NPM to pull this version directly from git if you specify the repository and commit hash in your package.json:

    "masonry-layout": "github:cliqqz/masonry#ffd2b614237176fd184b70b90a4559f9716dd29c",

I believe you also need to modify your package-lock as well for changes to take effect. You can view my implementation here: https://github.com/LittleBigRefresh/refresh-web/blob/master/package.json

Xyaren commented 9 months ago

For those looking for a workaround for Angular SSR while this PR becomes official, you can tell NPM to pull this version directly from git if you specify the repository and commit hash in your package.json:

    "masonry-layout": "github:cliqqz/masonry#ffd2b614237176fd184b70b90a4559f9716dd29c",

I believe you also need to modify your package-lock as well for changes to take effect. You can view my implementation here: https://github.com/LittleBigRefresh/refresh-web/blob/master/package.json

As I am using it as a peerDependency of ngx-masonry I was able to define an overwrite like this:

...
  "dependencies": {...},
  "devDependencies": {...},
  "overrides": {
    "ngx-masonry": {
      "masonry-layout": "github:cliqqz/masonry#ffd2b614237176fd184b70b90a4559f9716dd29c"
    },
...

https://docs.npmjs.com/cli/v8/configuring-npm/package-json#overrides

This requires a non-ancient npm version though.