Having trouble accessing Kotlin JS from JavaScript

I'm currently experiencing an issue where I am unable to call any Kotlin JS function and receiving an error stating that 'something' is not defined.

Initially, I attempted compiling the project with Gradle but found success after following this tutorial and compiling it with NPM. You can find my project attached here

EDIT: I tested it with Maven and it worked. However, since Maven is deprecated, I prefer using Gradle or NPM.

Here is the HTML code:

<body>
<script src="test.js"></script> // the file is generated in bin/bundle
<script>
    (function() {
        let a = new test.Test(); //test - module, Test - my class, the error occurs at this line
        a.test(); //test - method in the class Test
    })()
</script>
</body>

However, I always encounter:

Uncaught ReferenceError: test is not defined

The package.json looks like this:

{
  "name": "test",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "shx rm -rf bin && webpack && shx rm -rf bin/build/kotlin-test*",
    "test": "mocha bin/test"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "kotlin": "^1.3.70"
  },
  "devDependencies": {
    "@jetbrains/kotlin-webpack-plugin": "^3.0.2",
    "kotlin-test": "^1.3.70",
    "mocha": "^7.1.0",
    "shx": "^0.3.2",
    "webpack": "^4.42.0",
    "webpack-cli": "^3.3.11"
  },
  "description": ""
}

This is the webpack.config.js:

const KotlinWebpackPlugin = require('@jetbrains/kotlin-webpack-plugin');

module.exports = {
    entry: 'test', 

    resolve: {
        modules: ['bin/build', 'node_modules'], 
    },

    output: {
        path: __dirname + '/bin/bundle',
        filename: 'test.js', 
    },

    plugins: [
        new KotlinWebpackPlugin({
            src: __dirname,
            output: 'bin/test',
            moduleName: 'test',
            moduleKind: 'commonjs',
            librariesAutoLookup: true,
            packagesContents: [require('./package.json')],
        }),
        
        new KotlinWebpackPlugin({
            src: __dirname + '/src',
            output: 'bin/build',
            moduleName: 'test',
            moduleKind: 'commonjs',
            metaInfo: true,
            sourceMaps: true,
            librariesAutoLookup: true,
            packagesContents: [require('./package.json')],
        }),
    ],
};

And here's my class:

class Test {

    fun test() {
        println("test")
    }
}

EDIT: Here is the npm compilation of test.js:

(function (_, Kotlin) {
  'use strict';
  var println = Kotlin.kotlin.io.println_s8jyv4$;
  var Kind_CLASS = Kotlin.Kind.CLASS;
  function Test() {
  }
  Test.prototype.test = function () {
    println('test');
  };
  Test.$metadata$ = {
    kind: Kind_CLASS,
    simpleName: 'Test',
    interfaces: []
  };
  _.Test = Test;
  Kotlin.defineModule('test', _);
  return _;
}(module.exports, require('kotlin'))); //error: module is not defined

//# sourceMappingURL=test.js.map

The Maven Kotlin plugin output of test.js looks like this:

if (typeof kotlin === 'undefined') {
  throw new Error("Error loading module 'test'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'test'.");
}var test = function (_, Kotlin) {
  'use strict';
  var println = Kotlin.kotlin.io.println_s8jyv4$;
  var Kind_CLASS = Kotlin.Kind.CLASS;
  function Test() {
  }
  Test.prototype.test = function () {
    println('test');
  };
  Test.$metadata$ = {
    kind: Kind_CLASS,
    simpleName: 'Test',
    interfaces: []
  };
  _.Test = Test;
  Kotlin.defineModule('test', _);
  return _;
}(typeof test === 'undefined' ? {} : test, kotlin);

Answer №1

The moduleKind setting in the build.gradle file was incorrect. Changing it to 'plain' resolved the problem. Appreciate your help!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it more suitable for a library used by getStaticProps to be classified as a normal dependency or a dev

When working with NextJS's getStaticProps, I am implementing a library that is only utilized during build time. Should this library be categorized as a regular or development dependency in my package.json? ...

What causes the DOM to be updated upon each opening of the browser extension for Chrome?

Here is the default position: https://i.stack.imgur.com/tkWCA.png After checking it: https://i.stack.imgur.com/tdzbg.png When I click anywhere on the page to hide the dom extension output (without showing popup.html); However, when I reopen the extens ...

Upon initialization, navigate to the specified location in the route by scrolling

My page has various components stacked one after the other, such as: <about></about> <contact></contact> I am utilizing the ng2-page-scroll to smoothly scroll to a particular section when a navigation link is clicked. However, I a ...

How can I remove the div container every time the submit button is clicked?

I am currently working on a form that is capturing values as shown below. <form role="form" id="calculate"> <div class="form-group"> <select class="form-control" id="paper"> < ...

Tips on concealing modal popup when the page refreshes successfully

I implemented a progress modal popup to show progress for page reloads. This script is set to the master page and injects the progress modal popup when the form submit event is fired: <script type="text/javascript"> function ...

Inspection unsuccessful: port is already occupied for the Javascript automation project using WebdriverIO

I encountered the following error message while working in Visual Studio Code Debugger listening on ws://127.0.0.1:5859/325cc0fe-d885-4684-a4bf-03ec52ffd060 For help see https://nodejs.org/en/docs/inspector Starting inspector on 127.0.0.1:5859 faile ...

Synchronize data with Microsoft AJAX using force sync

When working with the Microsoft AJAX framework, I encounter a problem where my AJAX calls are asynchronous when I actually need them to be synchronous. I'm struggling to find a solution for this issue. In addition, I have been having difficulty findi ...

What is the best way to incorporate correct reference logic when utilizing Joi validation?

I am currently working on designing a straightforward schema to validate inputted number ranges. The condition is that the start value should be less than the end value, and conversely, the end value must be greater than the start value. Below is the sche ...

Ensure that the second y-axis in charts.js consistently shows the 100% tick

I have implemented a scatter chart using recharts and it currently looks like this: The right-y-axis in my chart represents the percentage and is showing the correct values as desired. However, I am looking to make a modification so that the 100% mark is ...

Incorporate a binary document into a JSPdf file

I am currently utilizing JsPDF to export HTML content into a downloadable PDF. Explore the following example which involves taking some HTML content and generating a downloaded PDF file using JsPdf import React from "react"; import { render } fro ...

Having trouble with the unresponsive sticky top-bar feature in Zurb Foundation 5?

According to the information provided on this website, it is recommended to enclose the top-bar navigation within a div element that has both the class "contain-to-grid" and "sticky". However, I have noticed that while the "contain-to-grid" class exists in ...

Why is my element still occupying space even though it has been hidden with a display of none?

Currently, I'm working on a dropdown navigation menu where one of the list items causes space issues when the display property is set to none. Specifically, the 'Book A Table' item isn't meant to be visible in the center div when the sc ...

Obtain the final result once all promises have been successfully resolved in a loop

Here is an array of IDs: let idsArray = [1, 2, 3, 4, 5]; How can I ensure that a promise is returned only after all calls made within the loop are completed? let deferredPromise = $q.defer(), finalResult = []; fo ...

Adjusting the width of the container <div> will automatically resize the inner <div> to match

I have a main container element. .wrapper{ border:1px solid blue; position:relative; top:20%; left:30%; height: 300px; width: 350px; } When I adjust the width of the parent container, the child box does not reposition itself accor ...

Unable to assign a value to a null property during the onchange event

I'm currently working on a project where I need to display flight details based on the selected flight number. To achieve this, I have created a dropdown menu that lists all available flight numbers and a table displaying various flight details such a ...

Managing User Feedback with Ajax, JQuery, and PHP

Imagine you're using ajax to send data. The server processes it (in PHP) and sends back a response that can be captured with complete: function(data) { //WRITE HTML TO DIV $('#somehing').html(data) } The big question is: how can you modify ...

Is there a way to reverse the upside-down text generated by OffscreenCanvas.getContext().fillText()?

When using OffscreenCanvas.getContext().fillText() to generate text and then OffscreenCanvas.transferToImageBitmap() to create a map, I noticed that the text appeared flipped upside down when applied as a texture in a threejs project. The image clearly sho ...

Executing the eslint command upon every save action

My package.json script is configured as follows: "scripts": { "lint": "eslint src webpack.config.js || exit 0" }, Is there a way to automate the execution of this lint command each time I save a file, eliminating the ...

Receive immediate updates of the text input in real-time using the onkeydown event handler in Javascript

I attempted to display the content of the input box in a message div simultaneously, however, the output always seems to be one step behind. function showWhatsWritten(){ var tempText; tempText = document.getElementById("text").value; document.getEle ...

Transmit ASP Webform data through Visual Studio to an external API

While working on a webform project in Visual Studio, I encountered an issue when trying to send data from the form fields to a 3rd party API using a POST request. Despite my attempts to use JSON to capture the form field data and send it as a JSON object, ...