# Set up a Kotlin/JS project Kotlin/JS projects use Gradle as a build system. To let developers easily manage their Kotlin/JS projects, we offer the `kotlin.multiplatform` Gradle plugin that provides project configuration tools together with helper tasks for automating routines typical for JavaScript development. The plugin downloads npm dependencies in the background using the [npm](https://www.npmjs.com/) or [Yarn](https://yarnpkg.com/) package managers and builds a JavaScript bundle from a Kotlin project using [webpack](https://webpack.js.org/). Dependency management and configuration adjustments can be done to a large part directly from the Gradle build file, with the option to override automatically generated configurations for full control. You can apply the `org.jetbrains.kotlin.multiplatform` plugin to a Gradle project manually in the `build.gradle(.kts)` file: Kotlin: ```KOTLIN plugins { kotlin("multiplatform") version "2.4.21" } ``` Groovy: ```GROOVY plugins { id 'org.jetbrains.kotlin.multiplatform' version '2.4.21' } ``` The Kotlin Multiplatform Gradle plugin lets you manage aspects of your project in the `kotlin {}` block of the build script: ```GROOVY kotlin { // ... } ``` Inside the `kotlin {}` block, you can manage the following aspects: * [Target execution environment](#execution-environments): browser or Node.js * [Set an ECMAScript target](#set-an-ecmascript-target): ES5, ES2015, or ES2020 * [Configure output granularity](#configure-output-granularity) * [Generation of TypeScript declaration files](#generation-of-typescript-declaration-files-d-ts) * [Project dependencies](#dependencies): Maven and npm * [Run configuration](#run-task) * [Test configuration](#test-task) * [Bundling](#webpack-bundling) and [CSS support](#css) for browser projects * [Target directory](#distribution-target-directory) and [module name](#module-name) * [Project's package.json file](#package-json-customization) ## Execution environments Kotlin/JS projects can target two different execution environments: * Browser for client-side scripting in browsers * [Node.js](https://nodejs.org/) for running JavaScript code outside a browser, for example, for server-side scripting. To define the target execution environment for a Kotlin/JS project, add the `js {}` block with `browser {}` or `nodejs {}` inside: ```KOTLIN kotlin { js { browser { } binaries.executable() } } ``` The instruction `binaries.executable()` explicitly instructs the Kotlin compiler to emit executable `.js` files. Omitting `binaries.executable()` will cause the compiler to only generate Kotlin-internal library files, which can be used from other projects but not run on their own. Tip: This is typically faster than creating executable files, and can be a possible optimization when dealing with non-leaf modules of your project. The Kotlin Multiplatform plugin automatically configures its tasks for working with the selected environment. This includes downloading and installing the required environment and dependencies for running and testing the application. This allows developers to build, run, and test simple projects without additional configuration. There is also an option to use an existing installation. Learn how to [use pre-installed Node.js](#use-pre-installed-node-js). ## Set an ECMAScript target Kotlin/JS can generate JavaScript for the ES5, ES2015, and ES2020 versions of the ECMAScript standard. Choose the newest version supported by your target environment: * `es5` provides compatibility with older JavaScript environments and is the default target. * `es2015` enables support for ES2015 features, including: * Modules that simplify your codebase and improve maintainability. * Classes that allow incorporating OOP principles, resulting in cleaner and more intuitive code. * Generators for compiling [suspend functions](https://kotlinlang.org/docs/composing-suspending-functions.html) that improve the final bundle size and help with debugging. * [JavaScript code inlining](js-interop.html#inline-javascript). * `es2020` includes all supported ES2015 features and allows the compiler to use ECMAScript 2020 features in the generated JavaScript code. For example, it compiles Kotlin `Long` values to JavaScript `BigInt` values. To configure an ECMAScript target, set the `target` property in the `build.gradle(.kts)` file. For example, to target ES2020: ```KOTLIN tasks.withType().configureEach { compilerOptions { target = "es2020" } } ``` Learn more about [ES5](https://262.ecma-international.org/5.1/), [ES2015](https://262.ecma-international.org/6.0/), and [ES2020](https://262.ecma-international.org/11.0/) standards. ## Configure output granularity You can choose how the compiler outputs `.js` files in your project: * One per module. By default, the JS compiler outputs separate `.js` files for each project module as a compilation result. * One per project. You can compile the whole project into a single `.js` file by adding the following line to the `gradle.properties` file: ```PROPERTIES # Default: per-module kotlin.js.ir.output.granularity=whole-program ``` * One per file. You can set up a more granular output that generates one (or two, if the file contains exported declarations) JavaScript file per each Kotlin file. To enable the per-file compilation mode: 1. Set `es2015` or `es2020` as the [compilation target](#set-an-ecmascript-target) to support ES2015 features in your project. 2. Add the following line to the `gradle.properties` file: ```PROPERTIES # Default: per-module kotlin.js.ir.output.granularity=per-file ``` ## Generation of TypeScript declaration files (`d.ts`) The Kotlin/JS compiler can generate TypeScript definitions from your Kotlin code. These definitions can be used by JavaScript tools and IDEs when working on hybrid applications to: * Provide autocompletion * Support static analyzers * Simplify the addition of Kotlin code in JavaScript and TypeScript projects Generating TypeScript definitions is especially valuable for the [business logic sharing use cases](js-overview.html#use-cases-for-kotlin-js). The compiler collects any top-level declarations marked with [@JsExport](js-to-kotlin-interop.html#jsexport-annotation) and automatically generates TypeScript definitions in a `.d.ts` file. To generate TypeScript definitions, explicitly configure it in your Gradle build file. Add the `generateTypeScriptDefinitions()` function to your `build.gradle.kts` file in the [js {} block](#execution-environments): ```KOTLIN kotlin { js { binaries.executable() browser { } generateTypeScriptDefinitions() } } ``` You can find the definitions in the `build/js/packages//kotlin` directory alongside the corresponding un-webpacked JavaScript code. ## Dependencies To declare a dependency, use the `dependencies {}` block in the `jsMain` source set in your `build.gradle(.kts)` file: Kotlin: ```KOTLIN kotlin { sourceSets { jsMain { dependencies { implementation("org.example.myproject:1.1.0") } } } } ``` Groovy: ```GROOVY kotlin { sourceSets { jsMain { dependencies { implementation 'org.example.myproject:1.1.0' } } } } ``` Only libraries that include artifacts for Kotlin/JS can be used as dependencies. To resolve dependencies, declare the repositories where Gradle should look for them in the `repositories {}` block of your `build.gradle(.kts)` file. For example: ```KOTLIN repositories { mavenCentral() } ``` If the library you are adding has dependencies on [packages from npm](#npm-dependencies), Gradle automatically resolves these transitive dependencies as well. ### Kotlin standard libraries The dependencies on the [standard library](https://kotlinlang.org/api/latest/jvm/stdlib/index.html) are added automatically. The version of the standard library is the same as the version of the Kotlin Multiplatform plugin. For multiplatform tests, the [kotlin.test](https://kotlinlang.org/api/latest/kotlin.test/) API is available. When you create a multiplatform project, you can add test dependencies to all the source sets by using a single dependency in `commonTest`: Kotlin: ```KOTLIN kotlin { sourceSets { commonTest.dependencies { implementation(kotlin("test")) // Brings all the platform dependencies automatically } } } ``` Groovy: ```GROOVY kotlin { sourceSets { commonTest { dependencies { implementation kotlin("test") // Brings all the platform dependencies automatically } } } } ``` ### npm dependencies In the JavaScript world, the most common way to manage dependencies is [npm](https://www.npmjs.com/). It offers the biggest public repository of JavaScript modules. The Kotlin Multiplatform Gradle plugin lets you declare npm dependencies in the Gradle build script, just how you declare any other dependencies. To declare an npm dependency, pass its name and version to the `npm()` function inside a dependency declaration. You can also specify one or multiple version ranges based on [npm's semver syntax](https://docs.npmjs.com/about-semantic-versioning). Kotlin: ```KOTLIN kotlin { sourceSets { jsMain { dependencies { implementation(npm("core-js", "^3.38.1")) } } } } ``` Groovy: ```GROOVY kotlin { sourceSets { jsMain { dependencies { implementation npm('core-js', '^3.38.1') } } } } ``` By default, the plugin uses a separate instance of the [Yarn](https://yarnpkg.com/lang/en/) package manager to download and install npm dependencies. It works out of the box without additional configuration, but you can [tune it to specific needs](#yarn). You can also work with npm dependencies directly using the [npm](https://www.npmjs.com/) package manager instead. To use npm as your package manager, in your `gradle.properties` file, set the following property: ``` kotlin.js.yarn=false ``` Besides regular dependencies, there are three more types of dependencies that can be used from the Gradle DSL. To learn more about when each type of dependency can best be used, have a look at the official documentation linked from npm: * [devDependencies](https://docs.npmjs.com/files/package.json#devdependencies), via `devNpm(...)`, * [optionalDependencies](https://docs.npmjs.com/files/package.json#optionaldependencies) via `optionalNpm(...)`, and * [peerDependencies](https://docs.npmjs.com/files/package.json#peerdependencies) via `peerNpm(...)`. Once an npm dependency is installed, you can use its API in your code as described in [Calling JS from Kotlin](js-interop.html). ## run task The Kotlin Multiplatform Gradle plugin provides a `jsBrowserDevelopmentRun` task that lets you run pure Kotlin/JS projects without additional configuration. For running Kotlin/JS projects in the browser, this task is an alias for the `browserDevelopmentRun` task (which is also available in Kotlin multiplatform projects). It uses the [webpack-dev-server](https://webpack.js.org/configuration/dev-server/) to serve your JavaScript artifacts. If you want to customize the configuration used by `webpack-dev-server`, for example, adjust the port the server runs on, use the [webpack configuration file](#webpack-bundling). For running Kotlin/JS projects targeting Node.js, use the `jsNodeDevelopmentRun` task that is an alias for the `nodeRun` task. To run a project, execute the standard lifecycle `jsBrowserDevelopmentRun` task, or the alias to which it corresponds: ```BASH ./gradlew jsBrowserDevelopmentRun ``` To automatically trigger a re-build of your application after making changes to the source files, use the Gradle [continuous build](https://docs.gradle.org/current/userguide/command_line_interface.html#sec:continuous_build) feature: ```BASH ./gradlew jsBrowserDevelopmentRun --continuous ``` or ```BASH ./gradlew jsBrowserDevelopmentRun -t ``` Once the build of your project has succeeded, the `webpack-dev-server` will automatically refresh the browser page. ## test task The Kotlin Multiplatform Gradle plugin automatically sets up a test infrastructure for projects. It downloads and installs the required test runners and other dependencies. For browser projects, you can choose between the [Karma](#karma) test runner and the new [DSL for browser testing](#dsl-for-browser-testing). For Node.js projects, the [Mocha](#node-js) test framework is available. The plugin also provides useful testing features, for example: * Source map generation * Test report generation * Test run results in the console ### Karma Warning: The Karma project has been [deprecated](https://github.com/karma-runner/karma#karma). No new features or bug fixes are expected. As an alternative for browser testing, try out the new [DSL for browser testing](#dsl-for-browser-testing). To configure the [Karma](https://karma-runner.github.io/) test runner, add the `useKarma {}` block inside the browser's `testTask` in your `build.gradle(.kts)` file. For example, to run tests against specific browsers, use: ```KOTLIN kotlin { js { browser { testTask { useKarma { useIe() useSafari() useFirefox() useChrome() useChromeCanary() useChromeHeadless() usePhantomJS() useOpera() } } } binaries.executable() // ... } } ``` Alternatively, you can add test targets for browsers in the `gradle.properties` file: ```TEXT kotlin.js.browser.karma.browsers=firefox,safari ``` This allows you to define a list of browsers for all modules and then add specific browsers in the build files of particular modules. The Kotlin Multiplatform Gradle plugin automatically generates a Karma configuration file at `build/js/packages/projectName-test/karma.conf.js` at build time. The file includes settings you set in the `useKarma {}` block in your build file. You can also place additional configuration files inside the `karma.config.d` directory at the root of your project. All `.js` configuration files in this directory are picked up and automatically merged into the generated `karma.conf.js` at build time. For more information on the Karma configuration, see [Karma's documentation](https://karma-runner.github.io/6.4/config/configuration-file.html). ### DSL for browser testing Kotlin offers an experimental DSL for running Kotlin/JS tests in a browser environment. It's designed to be technology-agnostic. The current implementation includes the following tools under the hood: * [Playwright](https://playwright.dev/) acts as a browser driver and a distribution manager that supports the Chromium, Firefox, and WebKit (Safari) browser engines. * [Mocha](https://mochajs.org/) acts as a test runner. * [webpack](https://webpack.js.org/) acts as a bundler (will be replaced with [Vite](https://vite.dev/) in [future releases](https://youtrack.jetbrains.com/issue/KT-48308/)). To try out the new DSL for browser testing, add the opt-in `test {}` block inside `browser {}` for your Kotlin/JS target: ```KOTLIN import org.jetbrains.kotlin.gradle.ExperimentalJsTestDsl import kotlin.time.Duration.Companion.seconds kotlin { js { browser { @OptIn(ExperimentalJsTestDsl::class) test { // Configures the default timeout for all runners with kotlin.Duration timeout = 30.seconds // Configures headless mode using Gradle providers headless = providers .environmentVariable("IS_IN_CI") .map { it.toBoolean() } .orElse(false) // Enables and configures a custom Chromium runner chromium("chromium-no-webgl2") { // Overrides the default timeout for this runner timeout = 10.seconds // Chromium-specific extra launch argument launchArgs.add("--disable-webgl2") } // Enables the Firefox runner firefox() // Enable WebKit (Safari) test runner webkit() // Enables and configures a custom WebKit runner webkit("headful") { headless = false } } } } } ``` For more information on the configuration of the new DSL for browser testing, see [Run tests in Kotlin/JS](js-running-tests.html#advanced-configuration). ### Node.js For Node.js projects, the Kotlin Multiplatform Gradle plugin automatically sets up the [Mocha](https://mochajs.org/) test framework. To specify environment variables used by your Node.js test runners (for example, to pass external information to your tests, or to fine-tune package resolution), use the `environment()` function with a key-value pair inside the `testTask {}` block in your build file: ```KOTLIN kotlin { js { nodejs { testTask { environment("key", "value") } } } } ``` ### Run tests By default, the Kotlin Multiplatform Gradle plugin uses [Headless Chrome](https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md) to run browser tests. No browsers are bundled with the plugin; test runners handle missing browsers differently: * With [Karma](#karma), any other browser should already be installed on your machine so that the plugin can use it to run tests. If you are executing Kotlin/JS tests on a continuous integration server, ensure that the browsers you want to test against are installed there as well. * With the new [DSL for browser testing](#dsl-for-browser-testing), the plugin installs the necessary browsers on the first run by using the [playwright install](https://playwright.dev/docs/browsers#install-browsers) command. Playwright manages the location of these browsers and doesn't use locally installed browsers. To run tests, execute the standard lifecycle `check` task: ```BASH ./gradlew check ``` If you want to skip tests, disable them in the `testTask {}` block in your build file: ```KOTLIN kotlin { js { browser { testTask { enabled.set(false) } } binaries.executable() // ... } } ``` ## webpack bundling For browser targets, the Kotlin Multiplatform Gradle plugin uses the widely known [webpack](https://webpack.js.org/) module bundler. ### webpack task The most common webpack adjustments can be made directly via the `kotlin.js.browser.webpackTask {}` configuration block in the Gradle build file: * `mainOutputFileName` − the name of the webpacked output file. It will be generated in `/build/kotlin-webpack//` after an execution of a webpack task. The default value is the project name. * `output.libraryTarget` − the module system for the webpacked output. Learn more about [available module systems for Kotlin/JS projects](js-modules.html). The default value is `umd`. ```GROOVY webpackTask { mainOutputFileName = "mycustomfilename.js" output.libraryTarget = "commonjs2" } ``` You can also configure common webpack settings to use in bundling, running, and testing tasks in the `commonWebpackConfig {}` block. ### webpack configuration file The Kotlin Multiplatform Gradle plugin automatically generates a standard webpack configuration file at the build time. It is located in `build/js/packages/projectName/webpack.config.js`. If you want to make further adjustments to the webpack configuration, place your additional configuration files inside a directory called `webpack.config.d` in the root of your project. When building your project, all `.js` configuration files will automatically be merged into the `build/js/packages/projectName/webpack.config.js` file. For example, To add a new [webpack loader](https://webpack.js.org/loaders/), add the following to a `.js` file inside the `webpack.config.d` directory: Note: In this case, the configuration object is the `config` global object. You need to modify it in your script. ```GROOVY config.module.rules.push({ test: /\.extension$/, loader: 'loader-name' }); ``` All webpack configuration capabilities are well described in its [documentation](https://webpack.js.org/concepts/configuration/). ### Building executables For building executable JavaScript artifacts through webpack, the Kotlin Multiplatform Gradle plugin contains the `jsBrowserDevelopmentWebpack` and `jsBrowserProductionWebpack` Gradle tasks. * `jsBrowserDevelopmentWebpack` creates development artifacts, which are larger but take little time to create. As such, use the `jsBrowserDevelopmentWebpack` tasks during active development. * `jsBrowserProductionWebpack` applies dead code elimination to the generated artifacts and minifies the resulting JavaScript file, which takes more time but generates executables that are smaller. As such, use the `jsBrowserProductionWebpack` task when preparing your project for production use. Execute either of these tasks to obtain the respective artifacts for development or production. The generated files will be available in `build/kotlin-webpack` unless [specified otherwise](#distribution-target-directory). ```BASH ./gradlew jsBrowserProductionWebpack ``` Note that these tasks will only be available if your target is configured to generate executable files (via `binaries.executable()`). To generate the distribution in the `build/dist//` directory, run the `jsBrowserDistribution` task instead: ```BASH ./gradlew jsBrowserDistribution ``` This task generates a ready-to-use distribution that includes the project resources. ## CSS The Kotlin Multiplatform Gradle plugin also provides support for webpack's [CSS](https://webpack.js.org/loaders/css-loader/) and [style](https://webpack.js.org/loaders/style-loader/) loaders. While all options can be changed by directly modifying the [webpack configuration files](#webpack-bundling) that are used to build your project, the most commonly used settings are available directly from the `build.gradle(.kts)` file. To turn on CSS support in your project, set the `cssSupport.enabled` option in the Gradle build file in the `commonWebpackConfig {}` block. This configuration is also enabled by default when creating a new project using the wizard. Kotlin: ```KOTLIN browser { commonWebpackConfig { cssSupport { enabled.set(true) } } } ``` Groovy: ```GROOVY browser { commonWebpackConfig { cssSupport { it.enabled = true } } } ``` Alternatively, you can add CSS support independently for `webpackTask {}`, `runTask {}`, and `testTask {}`: Kotlin: ```KOTLIN browser { webpackTask { cssSupport { enabled.set(true) } } runTask { cssSupport { enabled.set(true) } } testTask { useKarma { // ... webpackConfig.cssSupport { enabled.set(true) } } } } ``` Groovy: ```GROOVY browser { webpackTask { cssSupport { it.enabled = true } } runTask { cssSupport { it.enabled = true } } testTask { useKarma { // ... webpackConfig.cssSupport { it.enabled = true } } } } ``` Activating CSS support in your project helps prevent common errors that occur when trying to use style sheets from an unconfigured project, such as `Module parse failed: Unexpected character '@' (14:0)`. You can use `cssSupport.mode` to specify how encountered CSS should be handled. The following values are available: * `"inline"` (default): styles are added to the global `