Note: This gist is using the Kotlin legacy compiler, and is set to use Webpack version 4 in gradle.properties
. It may or may not work with the Kotlin IR compiler and Webpack version 5+.
build.gradle.kts accepts a 2 custom build arguments, -PbuildMode
and -PenvTarget
.
buildMode can be "DEBUG" (default) or "RELEASE". This determines whether the build process will run webpack in dev or prod configuration. Dev mode creates source maps, while prod mode minifies and does tree shaking and so on.
envTarget can be "DEV" (default) or "PROD". We will use this as an argument to the webpack build to select the correct set of env variables. If you need more options you can add more to the when
statement. This envTarget
is set as arguments to the webpack build and run tasks in kotlin { js { browser { } } }
This adds to the generated webpack.config a webpack.EnvironmentPlugin
that will allow you to access the environment variables in your code. We can set different variables for "DEV" vs "PROD".
This is a wrapper for the process
global variable in Javascript, so that we do not need to access our variables using js("process.env.<variable name>").
Definitions for each of the env variables so that they can be strictly typed and auto-completed in our Kotlin code.
Perfect, exactly what I was looking for. Thank you very much!