Kotlin/JS 라이브러리를 배포하고 통합하는 다양한 방법

Note that examples in this post use Kotlin 1.7.0



이전 Kotlin/JS 시리즈에서 @JsExport에 대해 배웠습니다. JS 측에 Kotlin 코드를 노출합니다. 이제 KMP 설정을 통해 JS 라이브러리 코드를 배포하는 다양한 방법을 살펴보겠습니다.

목차



  • Gradle Setup
  • Webpack

  • Node Module
  • npm-publish



  • Using the library

  • Use webpack executable
  • HTML
  • JavaScript
  • TypeScript


  • Use as node module
  • HTML
  • JavaScript
  • TypeScript



  • 그레이들 설정

    If you don't already have a JS target in your KMP library project, then you should check out first.

    Let's look at common options to use for JS target,

    js(IR) {
        browser()
        nodejs()
        binaries.library()
        binaries.executable()
    }
    
    • browser()
      It sets the JavaScript target execution environment as browser . It provides a Gradle task— jsBrowserTest that runs all js tests inside the browser using karma and webpack .

    • nodejs()
      It sets the JavaScript target execution environment as nodejs . It provides a Gradle task— jsNodeTest that runs all js tests inside nodejs using the built-in test framework.

    • binaries.library()
      It tells the Kotlin compiler to produce Kotlin/JS code as a distributable node library. Depending on which target you've used along with this, you would get Gradle tasks to generate library distribution files.

      Kotlin browser tasks
      --------------------
      jsBrowserDevelopmentLibraryDistribution
      jsBrowserDevelopmentLibraryPrepare
      jsBrowserProductionLibraryDistribution
      jsBrowserProductionLibraryPrepare
      
      Kotlin node tasks
      -----------------
      jsNodeDevelopmentLibraryDistribution
      jsNodeDevelopmentLibraryPrepare
      jsNodeDevelopmentRun
      jsNodeProductionLibraryDistribution
      jsNodeProductionLibraryPrepare
      jsNodeProductionRun
      jsNodeRun
      

      Either jsBrowserProductionLibraryDistribution or jsNodeProductionLibraryDistribution task generates output files in <YourLibModule>/build/productionLibrary folder

    • binaries.executable()
      It tells the Kotlin compiler to produce Kotlin/JS code as webpack executable .js files. Enabling this option generates the following Gradle tasks with the browser() environment.

      jsBrowserDevelopmentExecutableDistributeResources
      jsBrowserDevelopmentExecutableDistribution
      jsBrowserDevelopmentRun - start development webpack dev server
      jsBrowserDevelopmentWebpack - build webpack development bundle
      jsBrowserDistribution
      jsBrowserProductionExecutableDistributeResources
      jsBrowserProductionRun - start production webpack dev server
      jsBrowserProductionWebpack - build webpack production bundle
      jsBrowserRun
      jsBrowserWebpack
      

      Task jsBrowserDistribution generates webpack bundle js file along with .map file in <YourLibModule>/build/distributions folder.

    웹팩

    Webpack is a JS bundler tool . 모든 종속성을 결합하는 단일 실행 가능한 JS 파일을 생성할 수 있습니다.

    위의 Gradle 설정 섹션에서 볼 수 있듯이 Kotlin/JS browser()를 사용하여 단일 실행 파일로 라이브러리 및 binaries.executable() js(IR)의 옵션 표적. 기본적으로 번들 .js 파일 및 내보낸 라이브러리 이름은 모듈 이름과 동일합니다. 예를 들어, shared라는 모듈의 경우 shared.js 파일이 생성됩니다. exports.shared=... JS/TS 앱에서 이 라이브러리를 사용할 때 사용할 라이브러리의 이름을 반영합니다.

    ....."object"==typeof exports?exports.shared=n().....
    

    browser() 함수는 KotlinWebpack을 업데이트하는 데 사용할 수 있는 DSL을 제공합니다. 다양한 맞춤형 구성을 위한 작업. 예를 들어 아래와 같이 파일 및 라이브러리 이름을 변경할 수 있습니다.

    browser {
        webpackTask {
            outputFileName = "kmp_lib.js"
            output.library = "kmpLib"
        }
    }
    


    직접 더 많은 옵션을 탐색할 수 있습니다.

    노드 모듈

    Kotlin/JS library can also be published as a node module, and installed via npm in an app.

    As mentioned above in the Gradle setup section, when you run jsNodeProductionLibraryDistribution , it generates the following node-module related files,
    - .js file each for the library and all dependencies
    - .js.map file for each .js file
    - Typescript .d.ts file
    - package.json

    Note that node module cannot have upper case character in the name. An error or warning may appear if the module name has a capital character. We can declare a moduleName in the js(IR) target to avoid that,

    js(IR) {
        moduleName = "kmp-lib"
        ....
    }
    

    npm-publish 플러그인

    By default, there is no quick way to publish the library output as a node module to maven.

    npm-publish NPM 출판에 도움이 되는 인기 있는 라이브러리입니다. 또한 npmPublish 아래에 다양한 구성 옵션을 제공합니다. Gradle 작업.

    플러그인은 먼저 게시하지 않고 라이브러리를 로컬로 설치하는 데 사용할 수 있는 tarball을 생성합니다. packJsPackage 작업은 또한 tarball 콘텐츠 및 세부 정보의 읽을 수 있는 출력을 기록합니다.

    npm notice 
    npm notice 📦  [email protected]
    npm notice === Tarball Contents === 
    npm notice 291B  kmp-lib.d.ts                     
    npm notice 1.4kB kmp-lib.js                       
    npm notice 205B  kmp-lib.js.map                   
    npm notice 1.4kB kotlin-kotlin-stdlib-js-ir.js    
    npm notice 551B  kotlin-kotlin-stdlib-js-ir.js.map
    npm notice 95B   package.json                     
    npm notice === Tarball Details === 
    npm notice name:          shared                                  
    npm notice version:       0.1.0                                   
    npm notice filename:      shared-0.1.0.tgz                        
    npm notice package size:  1.6 kB                                  
    npm notice unpacked size: 3.9 kB                                  
    shared-0.1.0.tgz
    npm notice shasum:        c3c5e0a7a6d99cf1b7632fcfc4cef2e0b9052cb2
    npm notice integrity:     sha512-dZa4uNPRMjyny[...]JjzzNAiP7abHw==
    npm notice total files:   6                                       
    npm notice 
    


    게시할 계획이라면 Kotlin/JS 라이브러리를 노드 모듈로 사용한다면 이것은 프로젝트의 필수 플러그인입니다.


    라이브러리 사용

    We will now look at various ways to integrate the Kotlin/JS library into web applications.

    For example, we have a Greeting class and a greet() method under a package jabbar.jigariyo.kmplibrary

    package jabbar.jigariyo.kmplibrary
    
    import kotlin.js.JsExport
    
    @JsExport
    class Greeting {
        fun greet(): String {
            return "Hello, JS!"
        }
    }
    

    웹팩 실행 파일 사용

    We will now look at using the generated webpack binary executable bundle file in HTML and react JS app.

    HTML

    We can simply embed the js file as a script under the <script> tag of the HTML body.

    <html>
    
    <head>
        <meta charset="utf-8">
        <title>Including a External JavaScript File</title>
    </head>
    
    <body>
        <!-- Here I have copied the js file in the root folder of this html file -->
        <script type="text/javascript" src="kmp_lib.js"></script>
        <script>
            var kmpLib = this['kmpLib'];
            var greeting = new kmpLib.jabbar.jigariyo.kmplibrary.Greeting();
            console.log(greeting.greet());
        </script>
    </body>
    
    </html> 
    

    Two important things to note here are,

    • Using the library name to get a reference var kmpLib = this['kmpLib']
    • Getting reference of Greeting class using package name after the library reference kmpLib.jabbar.jigariyo.kmplibrary.Greeting()

    Once the html file is open in the browser, it would log Hello, JS! in console output.

    자바스크립트

    For the JavaScript example, I've a React app.

    To keep this simple, I've copied the distributions folder in the src directory of the React app.

    As the next step, import the library module in the App.js and use it

    import kmpLib from './distributions/kmp_lib';
    ......
    
    const greeting = new kmpLib.jabbar.jigariyo.kmplibrary.Greeting()
    console.log(greeting.greet())
    
    function App() {
      return (
        .......
      );
    }
    
    export default App;
    

    Once we run the app, Hello, JS! gets printed in the console and validates the integration with the library.

    Note that you might have to deal with configuring eslint if using React.

    타입스크립트

    It's not straightforward js Typescript에 타이프스크립트 정의가 없는 파일 앱.

    이 게시물의 범위를 벗어나므로 이 통합을 건너뛰었습니다.

    노드 모듈로 사용

    We will now look at installing and using the generated library files in a React JS and a TS app.

    To install the module locally, you can do npm install <PATH> . You can either use the path to the tarball ( .tgz ) file generated by the npm-publish plugin or the relative path to the build/productionLibrary folder of the kmp module.

    For example, the installation path for my sample looks like this,

    npm install ../shared/build/productionLibrary
    

    Once installed, the package.json would contain the library under the dependencies section,

    "dependencies": {
      "kmp-lib": "file:../shared/build/productionLibrary"
    }
    

    Note here that the name is the same as the moduleName we had defined earlier in the above gradle-setup section.

    HTML

    Using node module in plain HTML is out of scope for this post. There are techniques to make that work if you need to go that route.

    자바스크립트

    We should be able to import the library and use it once installed via npm


    App.js



    import kmpLib from 'kmp-lib';
    ......
    
    const greeting = new kmpLib.jabbar.jigariyo.kmplibrary.Greeting()
    console.log(greeting.greet())
    
    function App() {
      return (
         .....
      );
    }
    
    export default App;
    


    앱을 실행하면 Hello, JS! 콘솔에 인쇄되고 라이브러리와의 통합을 검증합니다.

    타입스크립트

    Just like the JavaScript example above, you have a reference of the library available after npm install .

    Importing in Typescript is slightly different as seen below


    main.ts



    import * as kmpLib from 'kmp-lib';
    
    let greeting = new kmpLib.jabbar.jigariyo.kmplibrary.Greeting()
    console.log(greeting.greet())
    


    실행하면 tsc main.ts 그리고 node main.js 터미널에서 명령을 실행하면 Hello, JS!가 표시됩니다. 인쇄.


    이 게시물에서는 먼저 Kotlin/JS 라이브러리를 웹팩 번들 또는 노드 모듈로 배포하는 방법을 배웠습니다. 나중에 HTML, JS 또는 TS 앱에 라이브러리를 통합하는 방법을 배웠습니다.


    읽어 주셔서 감사합니다! 질문이 있으면 댓글로 알려주세요. 또한 Twitter에서 나에게 연락하거나 Kotlin Slack . 이 모든 것이 흥미롭다면 work with 또는 work at 터치랩.

    좋은 웹페이지 즐겨찾기