Kotlin JS React accessing/configuring environment variables

After a bit more thinking, I see you can pass arbitrary values to the Webpack configuration (and so your Kotlin program in turn if desired) from the Gradle build using the Webpack environment variables feature (Webpack v4 docs – note the Kotlin plugin currently uses this version). To do this you also need to adjust the Webpack configuration file so that it exports a function. To illustrate:

//build.gradle.kts
kotlin {
   js { // Kotlin plugin v1.4 syntax
      browser {
         webpackTask {
            args.plusAssign( listOf( "--env.arbitraryValue=fortyTwo" ) )
            webpackConfigApplier {
               export = false // stops default export of config object in Webpack code
            } 
         }
      }
   }
}
//webpack.config.d/additional-config.js
module.exports = env => {
   
  const definePlugin = new webpack.DefinePlugin(
      {
         REPLACE_ME: env.arbitraryValue
      }
   )
   config.plugins.push(definePlugin)

   return config
}
// In the Kotlin program
val theAnswer = js("REPLACE_ME") // sets theAnswer = "fortyTwo"

That should then allow multiple setups in multiple environments.

3 Likes