4

In kotlin jvm (or in java, for what it matter) one can read resource content through the resource input stream.

Is there a way to do it in kotlin js? Right now I'm requesting the resource with an ajax call but It would be best to have the resources automatically embedded in the compiled javascript to avoid further server roundtrips. I'm aware of the triple quote string literal but It's not what I'm looking for.

Thanks for your suggestions

Jako
  • 2,489
  • 3
  • 28
  • 38

2 Answers2

5

You may add embedded data to javascript file by webpack. For example:

1) add file test.json to directory src/main/resources with content:

{
    "test123": 123
}

2) add directory src/main/resources to be resolve modules in webpack:

resolve: {
    modules: [
        path.resolve("src/main/resources")

    ]
}

3) add to main method code:

//require is external function: "external val require: dynamic"
println(JSON.stringify(require("test.json")))

And in output you will see: {"test123":123}

If you open webpack bundle, you will see that full file content of test.json is embedded to it like this:

function(t){t.exports={test123:123}}
Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40
kurt
  • 1,510
  • 2
  • 13
  • 23
4

Here's what I did to include svg files embedded in the JS file in Kotlin 1.5.31 + Webpack 5. Let's suppose we have a SVG file named star.svg in your src/jsMain/resources folder.

Project Root Folder/webpack.config.d/files.js (The files.js name doesn't matter)

config.module.rules.push(
    {
        test: /\.(svg)$/i,
        type: 'asset/source'
    }
);

Then in your code...

@JsModule("./star.svg")
@JsNonModule
external val star: dynamic

fun main() {
    console.log(star)
}

The print output is the contents of the star.svg file!

If you are curious about other available "type", check out https://webpack.js.org/guides/asset-modules/

MrPowerGamerBR
  • 514
  • 1
  • 6
  • 14