https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
a

Arkadii Ivanov

06/27/2022, 9:08 AM
I have a devtools Chrome extensions written in Kotlin, the UI is implemented with Compose for Web. The project is distributed as
browser()
+
binaries.library()
and everything works fine. Now I'm trying to replace Compose with React (
org.jetbrains.kotlin-wrappers:kotlin-react-dom
), and I'm getting the following runtime error:
Uncaught Error: Error loading module 'xyz'. Its dependency 'react-dom/client' was not found. Please, check whether 'react-dom/client' is loaded prior to 'xyz'.
If I use
binaries.executable()
then there is another runtime error:
Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'"
Is there a way to distribute a Chrome extension with React dependencies?
b

Big Chungus

06/27/2022, 10:42 AM
I'm guessing react wrappers are adding react-don as optional or peer dependency. Try adding it as npm dependency directly.
Binaries.library does not bundle other npm libs and instead declares them as node-externals. You could also have a look at generated webpack config and then try to remove all declared externals via webpack.config.d
Is your project open source? I could have a look if you still get stuck after trying these out
a

Arkadii Ivanov

06/27/2022, 10:48 AM
I believe I tried adding them as npm, but I will try once again. And yes, the project is open source. I will push to a branch a bit later, so you could check if you have spare time, I would appreciate that.
👍 1
b

Big Chungus

06/27/2022, 10:50 AM
Try the webpack bit then
Happy to have a peek when you're ready
a

Arkadii Ivanov

06/27/2022, 3:23 PM
You could also have a look at generated webpack config and then try to remove all declared externals via webpack.config.d
@Big Chungus Do you have an example how it can be done? For me, everything I put inside
webpack.config.d
directory looks ignored. Also is it applicable for
binaries.library()
?
b

Big Chungus

06/27/2022, 3:27 PM
Odd, I've used it with binaries.library just fine https://github.com/mpetuska/kmdc/tree/master/gradle/webpack.config.d
t

turansky

06/27/2022, 4:22 PM
Looks like compile output used instead of distribution output. If you use Kotlin Wrappers required NPM dependencies (
react
and
react-dom
in your example) will be available by default
b

Big Chungus

06/27/2022, 4:34 PM
Not quite. His problem is that chrome extensions do not resolve package.json and binaries.library does not bundle npm dependencies
@Ilya Goncharov [JB] Do you know where generated webpack.config.js for binaries.library() goes? Clearly it uses it for test task at least, but I can't find it in regular places (
^/build/js/packages/...
). Or does it not even use webpack for libraries anymore? I kinda assumed it was using webpack externals feature before, but now I feel that it might have been a wrong assumption. EDIT: for test task I found webpack config embedded into
karma.conf.js
, so that solves part of the mystery. But how exactly is the binary built?
FYI:
binaries.executable()
will not work here due to (I assume) missing main method since without it everything gets treeshaken
@Arkadii Ivanov you could hack it with
binaries.library()
by running webpack, rollup or any other bundler on the distribution task output manually.
i

Ilya Goncharov [JB]

06/27/2022, 4:54 PM
Hi, with
binaries.library()
webpack is not used. It is just compilation output (and with IR, all kotlin related modules are included into script) Moreover, it is the case to not use webpack and leave it as is (and integrate dependencies with own JS project with npm/yarn and bundle it with preferable way)
b

Big Chungus

06/27/2022, 4:57 PM
Ah, makes sense now, thanks. @Arkadii Ivanov looks like you'll need to post-process your distribution output with some bundler to convert it into "fat" js module manually
a

Arkadii Ivanov

06/27/2022, 4:57 PM
I have uploaded a simple reproducer, just in case - https://github.com/arkivanov/ChromeExtensionReproducer @Big Chungus Do you know any examples of the "fat" js?
b

Big Chungus

06/27/2022, 4:58 PM
Just building you one. Gimmie a sec
🙏 1
Ok, this might still need some tweaking, but try this MVP 1.
./gradlew jsBrowserProductionLibraryDistribution
2.
cd build/productionLibrary
3.
npx rollup <your_module_output_file_name>.js --file output.js --format iife
I'm using rollup here instead of webpack as it has most sensible defaults
You could also try parcel
Ok, some tweaks are needed afterall. Replace your build.gradle.kts with this
plugins {
  kotlin("js")
}

kotlin {
  js(IR) {
    browser()
    binaries.library()
  }
}

dependencies {
  implementation("org.jetbrains.kotlin-wrappers:kotlin-react")
  implementation("org.jetbrains.kotlin-wrappers:kotlin-react-dom")
  implementation("org.jetbrains.kotlin-wrappers:kotlin-styled")
  implementation("org.jetbrains.kotlin-wrappers:kotlin-extensions")
  implementation("org.jetbrains.kotlin-wrappers:kotlin-emotion")
  implementation("org.jetbrains.kotlin-wrappers:kotlin-mui")
  implementation("org.jetbrains.kotlin-wrappers:kotlin-mui-icons")
  implementation(enforcedPlatform("org.jetbrains.kotlin-wrappers:kotlin-wrappers-bom:1.0.0-pre.348"))

  // New stuff
  implementation(npm("react-dom", "*"))
  implementation(npm("@mui/material", "*"))
  implementation(npm("react", "*"))
  implementation(npm("@emotion/react", "*"))
  implementation(npm("@emotion/styled", "*"))
  implementation(devNpm("rollup", "*"))
  implementation(devNpm("@rollup/plugin-commonjs", "*"))
  implementation(devNpm("@rollup/plugin-node-resolve", "*"))
}
Run
./gradlew jsBrowserProductionLibraryDistribution
Then
cd build/productionLibrary
Then
yarn install
And finally
yarn rollup ChromeExtensionReproducer-chrome-extension.js --file _out.js --format iife --plugin @rollup/plugin-commonjs --plugin @rollup/plugin-node-resolve
After that your "fat-lib" will be at
_out.js
Ping me if you want to discuss what's happening in more details
a

Arkadii Ivanov

06/27/2022, 6:58 PM
Thanks! I did everything as described and got the fat jar. The extension now crashes with another error:
Uncaught ReferenceError: process is not defined
This looks like the produced code is for server (node), not browser. Overall this looks quite complicated. Maybe I should stick with Compose and without any npm dependencies for now? I won't be able to use
mui
either, I guess. The whole reason why I am replacing Compose with React is because I wanted Kotlin 1.7.0, and converting Compose -> React is trivial in my case.
By the way, the LEGACY mode works out of the box without any workarounds. I will consider switching to legacy for now.
b

Big Chungus

06/27/2022, 7:03 PM
Yes, because LEGACY ignores your binaries and just embeds everything all the time
Simpler times... 😄
1
As for the error, it's indeed strange. You could probably get rid of process references with some more rollup config, but at this point I'd either wait for CfW 1.7.0 or just switch back to legacy backend
🙏 1
I suspect react references process for some SSR parts and webpack normally removes that
Surely rollup can do that too or you could try bundling it with webpack instead
a

Arkadii Ivanov

06/27/2022, 7:06 PM
Thanks @Big Chungus for your efforts to help me!
b

Big Chungus

06/27/2022, 7:06 PM
But this is now entirely js ecosystem and has nothing else to do with kjs
No worries. I found it quite interesting myself.
Wait, one quick hack. Append
window.process = window
to the very top of your fat-bundle. See if that hacks it 😄
Otherwise, I'm 99% sure this extra plugin would fix it too https://www.npmjs.com/package/rollup-plugin-inject-process-env
React is known to rely on process.NODE_ENV a lot
Probably not the most scalable solution at this point, but now I'm curious to see if it could. Don't even care if it should 😄
a

Arkadii Ivanov

06/27/2022, 7:23 PM
window.process = window
results in
uncaught TypeError: window is not a function
🙃
b

Big Chungus

06/27/2022, 7:24 PM
What's the global object for extensions?
For regular webapp it's window
For nodejs app it's process
Try with this. You build now with
yarn rollup -c
a

Arkadii Ivanov

06/27/2022, 7:38 PM
I see that
window
is defined, I'm able to show an alert
Try with this.
It works now without errors! Thanks again!
b

Big Chungus

06/27/2022, 7:47 PM
Wow, I did not expect to get it working to be honest 😄
😂 1
I should probably documment all this in a blogpost eventually... Would you interested to collaborate? I have no clue how web extensions are developed...
a

Arkadii Ivanov

06/27/2022, 7:57 PM
@Big Chungus I would love to! But I have little experience in web dev overall.
b

Big Chungus

06/27/2022, 7:57 PM
I'll cover web dev part, you can just append extension dev bit
👍 1
i.e. what files are needed and why
I'll ping you with the draft of what I do know
a

Arkadii Ivanov

06/27/2022, 7:58 PM
Sounds good! Overall, it feels that there is a use case for bundling npm deps in a library project. Would be good to have a configuration or a Gradle task for it.
b

Big Chungus

06/27/2022, 7:59 PM
Absolutely, wanna raise an issue?
Although looks like it would be a pretty big change for KGP since binaries.library() does not use webpack at all right now
t

turansky

06/27/2022, 8:04 PM
bundling npm deps in a library project
It looks like
executable
distribution
b

Big Chungus

06/27/2022, 8:06 PM
There are subtle differences. Executables must have an entrypoint, libraries usually don't
Also he did try binaries.executable() and that didn't quite work due to unsafe eval usage for whatever reason
But I do agree that this particular use-case should be covered by the executable and not a library
a

Arkadii Ivanov

06/27/2022, 8:09 PM
Something like
binaries.library { bundle = true }
would be nice to have. Maybe worth filing a ticket.
I have also tried webpack and I find it easier to use in this particular case. My steps: 1. Run
./gradlew :chrome-extension:browserProductionLibraryDistribution
2.
cd chrome-extension/build/productionLibrary
3.
npm install
4.
npx webpack --config ../../webpack.config.js
The config file:
const path = require('path');

module.exports = {
    entry: './ChromeExtensionReproducer-chrome-extension.js',
    target: 'web',
    mode: 'production',
    output: {
        path: path.resolve(__dirname, 'build/dist'),
        filename: 'ChromeExtensionReproducer-chrome-extension.js',
    },
};
👍 1
b

Big Chungus

06/28/2022, 10:40 PM
Yeah i started with rollup hoping to avoid config file but in the end webpack turned out to be simpler as it did not need plugins
a

Arkadii Ivanov

07/02/2022, 5:12 PM
I have also noticed the following change after upgrading Kotlin from 1.6.10 to 1.7.0. When assembling
binaries.library()
via
jsBrowserDevelopmentLibraryDistribution
on Kotlin 1.6.10, all Kotlin dependencies (other Kotlin modules from my project, coroutines, atomicfu, etc.) are bundled inside the resulting
.js
file. So if I don't have any NPM direct or transitive dependencies, then there is only one single
.js
file created with everything bundled. But on Kotlin 1.7.0 there is separate
.js
file per each dependency:
kotlinx.coroutines-kotlinx-coroutines-core-js-ir.js
,
88b0986a7186d029-atomicfu-js-ir.js
, and also files for each of my project's modules. Is this change intentional?
b

Big Chungus

07/02/2022, 5:15 PM
It is, there used yo be a compiler flag for that
Note that it only applies to kjs dependencies, not npm
a

Arkadii Ivanov

07/02/2022, 5:17 PM
Do you remember the name of the flag?
b

Big Chungus

07/02/2022, 5:18 PM
-Xir-per-module i think
That would enable 1.7.0 behaviour
a

Arkadii Ivanov

07/02/2022, 5:21 PM
So now this flag is always enabled, and this is the new behavior, and there is no switch off?
b

Big Chungus

07/02/2022, 5:22 PM
I'd assume so
Maybe try setting to false explicitly
👍 1
a

Arkadii Ivanov

07/02/2022, 5:30 PM
So, this mode is enabled by default since
1.6.20
. To switch it off:
# gradle.properties
kotlin.js.ir.output.granularity=whole-program // `per-module` is the default
b

Big Chungus

07/02/2022, 5:33 PM
Awesome to know!
a

Arkadii Ivanov

07/02/2022, 5:34 PM
Well, with this parameter in gradle.properties, the resulting js file has all modules bundled indeed. But there are still separate js files produced for each module (that perhaps unused?).
b

Big Chungus

07/02/2022, 5:35 PM
Did you clean before build?
a

Arkadii Ivanov

07/02/2022, 5:36 PM
Yep
Oh no, I cleaned only the app's build folder. After
./gradlew clean
everything is good! Thanks!
😄 1
Just in case someone wants Gradle tasks to webpack
binaries.library()
. I'm using the following snippet by running
./gradlew browserLibraryBundle
, the output is in
build/dist
folder.
b

Big Chungus

07/02/2022, 7:13 PM
You could also hook into KGP nodejs executable and setup tasks to avoid needing a separate global nodejs installation on the machine
🔥 1
a

Arkadii Ivanov

07/02/2022, 7:16 PM
Thanks!