Using jQuery with kotlin and gradle (JS backend)

  gradle, javascript, jquery, kotlin

I’m currently trying to get a simple example running in which jQuery can be used by kotlin code compiled to JS with the help of gradle. So far I pieced together the following elements which should be enough according to older descriptions using the kotlin.js.externals:kotlin-js-jquery:3.2.0-0 package by adding it like this to the build.gradle.kts of the project:

repositories {
    ...
    mavenCentral()
    maven(url = uri("https://kotlin.bintray.com/js-externals"))
}

dependencies {
    implementation("kotlin.js.externals:kotlin-js-jquery:3.2.0-0")
}

After adding the package I can sucessfully import the corresponding kotlin package in a simple Kotlin file like this:

import js.externals.jquery.jQuery

fun main() {
    console.log(jQuery("div"))
}

But this sadly fails if executed with the following stack trace in the JS console:

Uncaught TypeError: $module$jquery is not a function
    at main (simple.kt?9d2a:4)
    at Object.eval (yet_another_one.js:14)
    at eval (yet_another_one.js:5)
    at eval (yet_another_one.js:8)
    at Object../kotlin-dce-dev/yet_another_one.js (yet_another_one.js:515)
    at __webpack_require__ (yet_another_one.js:30)
    at Object.0 (yet_another_one.js:527)
    at __webpack_require__ (yet_another_one.js:30)
    at yet_another_one.js:94
    at yet_another_one.js:97

After this I checked the packages webpack used for the bundling and I found out that as soon as the kotlin.js.externals:kotlin-js-jquery:3.2.0-0 package is used the following jquery.js file gets used instead of the one with the actual code:

(function (root, factory) {
  if (typeof define === 'function' && define.amd)
    define(['exports', 'kotlin'], factory);
  else if (typeof exports === 'object')
    factory(module.exports, require('kotlin'));
  else {
    if (typeof kotlin === 'undefined') {
      throw new Error("Error loading module 'jquery'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'jquery'.");
    }
    root.jquery = factory(typeof jquery === 'undefined' ? {} : jquery, kotlin);
  }
}(this, function (_, Kotlin) {
  'use strict';
  Kotlin.defineModule('jquery', _);
  return _;
}));

//# sourceMappingURL=jquery.js.map

As this looks a bit strange to me as the jquery code seems not to be found anywhere I also tried adding it as a NPM dependency to the build.gradle.kts like this:

dependencies {
    ...
    implementation(npm("jquery", "3.6.0"))
}

But doing so didn’t change a thing. Webpack still uses the jquery.js file shown above (and maybe rightfully so), but it also still doesn’t work.

I would appreciate any help to get this working as I already invested a lot of time in it and I’m currently kinda hopeless :(.

Thanks a lot!

Source: Ask Javascript Questions

LEAVE A COMMENT