Okay, so I am experimenting with the Kotlin 1.4-M1 pre-release, and am fully aware that it is beta. However, on reading that it can generate .d.ts files I was so excited I started a very small Hello World example. But no matter what I try I can’t get it to work in a React Typescript project. The modules are undefined, or something else is not found.
I tried nodejs()
target, browser()
target, tried different module systems. Everytime I get a nice .d.ts file like this:
declare namespace greeter_test_web {
type Nullable<T> = T | null | undefined
class Greeter {
constructor(from: string)
readonly from: string;
greet(to: string): string
}
}
and a JS file that looks like:
(function (root, factory) {
if (typeof define === 'function' && define.amd)
define(['exports'], factory);
else if (typeof exports === 'object')
factory(module.exports);
else
root['greeter-test-web'] = factory(typeof this['greeter-test-web'] === 'undefined' ? {} : this['greeter-test-web']);
}(this, function (_) {
'use strict';
function Greeter(from) {
{
this._from = from;
}
}
Greeter.prototype._get_from_ = function () {
return this._from;
};
Greeter.prototype.greet = function (to) {
return '' + 'Hello ' + to + ' from ' + this._from + '!!';
};
Greeter.$metadata$ = {
simpleName: 'Greeter',
kind: 'class',
interfaces: []
};
Object.defineProperty(Greeter.prototype, 'from', {
get: Greeter.prototype._get_from_
});
_.Greeter = Greeter;
return _;
}));
I create a React page like follows:
import React from 'react';
import './App.scss';
import "greeter-test-web";
const App : React.FunctionComponent = () => {
const greeter = new greeter_test_web.Greeter("Kotlin/JS")
return <h1>{ greeter.greet("world")}</h1>
}
export default App;
Please note that WebStorm autocompletes everything here in the tsx file.
But the result is everytime: “greeter_test_web” is not defined.
Does anyone have any pointers in how to get this simple example up and running?
EDIT:
I got it working! With type hinting.
It is a CommonJS module ofcourse…I don’t really like mixing in CommonJS in frontend projects like this.
import React from 'react';
import './App.scss';
const greeter_test_web = require("greeter-test-web"); // NOTE: don't rename te const to something else or type hinting doesn't work.
const App : React.FunctionComponent = () => {
const greeter = new greeter_test_web.Greeter("Kotlin/JS");
return <h1>{ greeter.greet("World") }</h1>
}
export default App;