jcraane / kmm-resources

Gradle plugin for generating localizable resources for Android, iOS and Web in a Kotlin Multiplatform (Mobile) project for use in the UI, android, iOS and shared framework code.
Apache License 2.0
28 stars 6 forks source link

`window.navigator` usage prevents usage of generated JS in next.js #10

Open manmal opened 2 years ago

manmal commented 2 years ago

Unfortunately, window is not available in next.js - at least not for components that support server-side rendering. Currently, importing the JS module generated by kmm-resources results in next.js compilation errors. I tried mocking window.navigator with an almost empty object to avoid this, but next.js just responded with a different compilation error.

A fix that works (tested by cloning kmm-resources, making the code changes and using includeBuild) is to remove the browserLanguage fallback, i.e. eliminating usage of window.navigator completely. The next.js project builds just fine with the resulting JS code. However, this would remove existing functionality, and I see how this could be unacceptable.

I thought that an alternative could be to replace window with global scope, like:

val browserLanguage = navigator.languages.firstOrNull()

instead of

val browserLanguage = window.navigator.languages.firstOrNull()

The reasoning would be that navigator (in some frameworks global.navigator) is easier to mock in environments like next.js (though I'm not yet sure it would work!). But the proposed change might not be possible because kotlinx seems to provide no possibility to access global scope variables (?).

Any ideas for other workarounds or refactorings are appreciated, I'd be happy to make a subsequent pull request.

jcraane commented 2 years ago

Thanks for reporting the issue. We are going to look into the issue. We also happy to receive a PR for this if you want.

manmal commented 2 years ago

@jcraane I haven't managed to find another workaround so far. Would you be open to removing the browserLanguage fallback? I can open a PR for that.

jcraane commented 2 years ago

Yeah, sure. If you create a PR for that I will have a look at it.