Kotlin多平台库JS目标下如何导入jsMain目录文件?
libphonenumber-js in Kotlin/JS (jsMain Source Set) After adding the npm dependency via Gradle, you need to create external declarations to bridge Kotlin to the JavaScript library's API. Here's how to do it:
Step 1: Create an External Declaration File
In your src/jsMain/kotlin directory (under your project's package structure), create a new Kotlin file (e.g., LibPhoneNumber.kt). This file will define Kotlin-compatible interfaces for the JS library's functionality.
Step 2: Add External Annotations and Declarations
Use @JsModule to link directly to the npm package, and the external keyword to mark Kotlin declarations that map to JavaScript code. For libphonenumber-js, here's a basic example covering common use cases:
package com.yourpackage // Replace with your actual package name @JsModule("libphonenumber-js") @JsNonModule external object LibPhoneNumber { // Maps to the JS function `parsePhoneNumber` fun parsePhoneNumber(number: String, countryCode: String): PhoneNumber // Add other needed functions, e.g.: fun isValidNumber(number: String, countryCode: String): Boolean } // Interface representing the PhoneNumber object returned by the JS library external interface PhoneNumber { fun format(formatType: String): String // Accepts values like "INTERNATIONAL" or "NATIONAL" val country: String val number: String val isValid: Boolean }
Step 3: Import and Use in jsMain Code
You can now import the external declaration in any Kotlin file under jsMain and use the library like regular Kotlin code:
package com.yourpackage fun processPhoneNumber(rawNumber: String, country: String) { val phoneNumber = LibPhoneNumber.parsePhoneNumber(rawNumber, country) if (phoneNumber.isValid) { println("Formatted number: ${phoneNumber.format("INTERNATIONAL")}") println("Associated country: ${phoneNumber.country}") } else { println("Invalid phone number provided") } }
Key Notes:
- Adjust the external declarations to match the exact API of
libphonenumber-js(reference the library's JavaScript documentation for all available functions and properties). - If the library used default exports instead of named exports, you would add
@JsName("default")to your external declaration. Forlibphonenumber-js, named exports are standard, so the example above works as-is. - Ensure your package names are consistent across declaration files and usage code to avoid import errors.
内容的提问来源于stack exchange,提问作者Anmol Singh Sahi

