greggman / twgl.js

A Tiny WebGL helper Library
http://twgljs.org
MIT License
2.67k stars 260 forks source link

Error in server side runtime #114

Closed arfianadam closed 5 years ago

arfianadam commented 5 years ago

This code: https://github.com/greggman/twgl.js/blob/master/src/textures.js#L1012-L1029

Runs in server side's runtime because it is immediately executed instead of being executed when needed. This behavior can produce error like this:

Server preload error: ReferenceError: location is not defined
[1]     at ../node_modules/twgl.js/dist/4.x/twgl-full.js:8139:31
[1]     at Object../src/textures.js (../node_modules/twgl.js/dist/4.x/twgl-full.js:8145:2)
[1]     at __webpack_require__ (../node_modules/twgl.js/dist/4.x/twgl-full.js:35:30)
[1]     at Object../src/twgl.js (../node_modules/twgl.js/dist/4.x/twgl-full.js:9023:40)
[1]     at __webpack_require__ (../node_modules/twgl.js/dist/4.x/twgl-full.js:35:30)
[1]     at Object../src/twgl-full.js (../node_modules/twgl.js/dist/4.x/twgl-full.js:8979:13)
[1]     at __webpack_require__ (../node_modules/twgl.js/dist/4.x/twgl-full.js:35:30)
[1]     at ./src/attributes.js.exports.__esModule (../node_modules/twgl.js/dist/4.x/twgl-full.js:99:18)
[1]     at ../node_modules/twgl.js/dist/4.x/twgl-full.js:102:10
[1]     at webpackUniversalModuleDefinition (../node_modules/twgl.js/dist/4.x/twgl-full.js:8:20)

I proposed a PR that makes this function run only when needed (it's not like it runs a tremendous amount of times in a fraction of a second anyway). Or if you have other thoughts on this please let me know!

greggman commented 5 years ago

Can you explain why you're running it on the server? It looks like the issue is regardless of which path it takes it expects a global location object which exists in both browser pages and browser workers but not in servers. So, your fix will make it not error on load but it will still error if you try to load a texture on the server and no global location object exists.

Should the fix check for location on top of document so you could actually load a texture on the server? Of course it also relies on Image and or fetch/createBitmapImage which also don't exist on the server.

I guess what am asking is either

  1. The fix is fine. If you want to load textures from urls you should make sure global location, Image and/or fetch and createBitmapImage exist before calling.

  2. The fix should check that a global location exists

thoughts?

sghall commented 5 years ago

@greggman I ran into this issue as well.

Many react apps, for example, do SSR (server-side rendering) which generates the page HTML by rendering the entire tree of components for that URL. If TWGL is in the Javascript bundle for that page it's going to throw an error. Of course, no WebGL stuff is going to render on the server, but the javascript does get loaded.

arfianadam commented 5 years ago

Sorry, but @sghall explained it better. Thanks!