Elderjs / elderjs

Elder.js is an opinionated static site generator and web framework for Svelte built with SEO in mind.
https://elderguide.com/tech/elderjs/
MIT License
2.11k stars 53 forks source link

Defined value for 'this' - how to achieve? #228

Open doubtx opened 2 years ago

doubtx commented 2 years ago

Hello, I am using external Carousel library called 'glider-js' In Glider JS code there is a check if window is defined and if not - it falls back to 'this':

However, when request is served on server side (via "npm run dev") or during the build process, this is also not defined so I am getting error:

TypeError: Cannot set property 'Glider' of undefined
    at /Users/oleg/Projects/general/elderjs-app-debug/___ELDER___/compiled/components/Clock.js:74:32
    at /Users/oleg/Projects/general/elderjs-app-debug/___ELDER___/compiled/components/Clock.js:66:27
    at /Users/oleg/Projects/general/elderjs-app-debug/___ELDER___/compiled/components/Clock.js:68:3
    at createCommonjsModule (/Users/oleg/Projects/general/elderjs-app-debug/___ELDER___/compiled/components/Clock.js:36:9)
    at Object.<anonymous> (/Users/oleg/Projects/general/elderjs-app-debug/___ELDER___/compiled/components/Clock.js:59:14)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Module.require (internal/modules/cjs/loader.js:974:19)
/ [

I have already tried to play with 'hydrate-client' and tried to set rollup context to 'this'. Seems issue is not really related to rollup, as

npm run build:rollup 

runs ok

You can reproduce the issue as follows:

<!-- routes/home/Home.svelte  -->
<script>
  import Glider from 'glider-js';
</script>

PS. It all works perfectly on Svelte Kit + Vite, so maybe Rollup can be the reason, but then I dont understand how exactly

nickreese commented 2 years ago

Glider will probably only work on the client side. I’m mobile but look at the docs for “browser” and you should be able to limit it’s execution to just the browser.

doubtx commented 2 years ago

Hey, @nickreese I cant inject any check for third part lib to validate if it is running on browser or not

eight04 commented 2 years ago

This is a common issue when we try to share the same code between the server and the client.

Ideally, we only need to import the library in client build. However, there is no way to apply conditions to import statements.

You can try to guard the code and configure treeshake.moduleSideEffects option in rollup. Maybe it will trim the module when it is not used.