You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin多平台库JS目标下如何导入jsMain目录文件?

Importing 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. For libphonenumber-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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 02:57:51