### Install and Run stc CLI Source: https://github.com/scalablytyped/converter/blob/master/docs/cli.md Install the stc command using the coursier runner and run it in a directory containing package.json and node_modules. ```bash cs install stc stc ``` -------------------------------- ### Usage Examples for Different Flavors Source: https://context7.com/scalablytyped/converter/llms.txt Demonstrates how to use converted React components after conversion, showing distinct syntax for Slinky and Japgolly (scalajs-react). ```scala // Usage after conversion — components are in the components package import typings.antd.components.Button import typings.antd.components.Input // Slinky usage Button("Click me") // Japgolly (scalajs-react) usage Button() // returns ReactElement, integrate with .render() ``` -------------------------------- ### TypeScript Type Mappings Usage Examples Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md Provides concrete examples of using TypeScript's Partial, Pick, and Record utility types with an interface. ```typescript interface Person { age: number; name: string; } // these compile const named: Pick = {name: "asdasd"}; const empty: Partial = {}; const record: Record<"a" | "b", number> = {a: 1, b: 2} ``` -------------------------------- ### Instantiable Interface Example Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md Demonstrates the use of Instantiable interfaces to represent newable JavaScript classes in Scala.js, including instantiation. ```scala trait Instantiable1[T1, R] extends js.Object object Instantiable1 { @inline implicit final class Instantiable1Opts[T1, R](private val ctor: Instantiable1[T1, R]) extends AnyVal { @inline def newInstance1(t1: T1): R = js.Dynamic.newInstance(ctor.asInstanceOf[js.Dynamic])(t1.asInstanceOf[js.Any]).asInstanceOf[R] } } ``` ```scala @js.native trait Window { var Blob: Anon_BlobParts = ??? } @js.native trait Anon_BlobParts extends ScalablyTyped.runtime.Instantiable0[Blob] with ScalablyTyped.runtime.Instantiable1[/* blobParts */ js.Array[BlobPart], Blob] with ScalablyTyped.runtime.Instantiable2[/* blobParts */ js.Array[BlobPart], /* options */ BlobPropertyBag, Blob] //usage val blob: Blob = typings.std.window.Blob.newInstance0() ``` -------------------------------- ### JQueryUI Integration Example Source: https://github.com/scalablytyped/converter/blob/master/docs/usage.md For libraries like JQueryUI that monkey-patch existing libraries, ensure `typings.jqueryui.jqueryuiRequire` is touched. Then, cast `typings.jquery.JQuery` to `typings.jqueryui.JQuery`. ```scala import typings.jquery.JQuery import typings.jqueryui.JQuery as JQueryUi typings.jqueryui.jqueryuiRequire (someJQueryInstance as JQueryUi) ``` -------------------------------- ### Use Yarn Instead of NPM Source: https://github.com/scalablytyped/converter/blob/master/docs/plugin.md Configure the plugin to use Yarn for managing npm dependencies instead of npm by setting `useYarn` to true in your `build.sbt`. Ensure Yarn is installed on your system. ```scala project.settings( useYarn := true ) ``` -------------------------------- ### Import React Components in Scala Source: https://github.com/scalablytyped/converter/blob/master/docs/flavour.md Import React components from the generated libraries after configuring the flavour. This example shows importing an Ant Design Button component. ```scala import typings.antd.components.Button ``` -------------------------------- ### TypeScript Interface Augmentation Example Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md Shows how TypeScript allows augmenting existing interfaces across different modules. This is a common pattern for extending library functionality. ```typescript // in library foo interface FooStatic { sayHello(); } // in library foo-augmented interface FooStatic { sayGoodbye(); } import foo from 'foo'; import 'augments-foo'; foo.sayGoodbye(); ``` -------------------------------- ### Implement externalNpm task Source: https://github.com/scalablytyped/converter/blob/master/docs/plugin-no-bundler.md Implement the externalNpm task to manage your npm or yarn dependencies. This example executes 'yarn' and returns the base directory of the sbt project. ```scala import scala.sys.process._ project.settings( externalNpm := { Process("yarn", baseDirectory.value).! baseDirectory.value } ) ``` -------------------------------- ### Scala.js @js.native Annotated Trait Example Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md Demonstrates how to instantiate a @js.native annotated trait by casting a dynamic literal. This is a workaround for consuming types that cannot be directly translated. ```scala js.Dynamic.literal(foo = 1).asInstanceof[Props] ``` -------------------------------- ### Specify stdlib for TypeScript compiler Source: https://github.com/scalablytyped/converter/blob/master/docs/conversion-options.md Use `stStdlib` to specify the TypeScript stdlib versions to be used. This controls which DOM/Javascript APIs are available during conversion. For example, a Node.js application might not need DOM APIs. ```scala project.settings( stStdlib := List("es6", "es2018.asyncgenerator") ) ``` -------------------------------- ### Run ScalablyTyped Converter with Demo Set Source: https://github.com/scalablytyped/converter/blob/master/CLAUDE.md Execute the converter with the demo set enabled. This command includes flags for soft writes, parse cache, and offline mode. ```bash sbt "importer/runMain org.scalablytyped.converter.Main -softWrites -enableParseCache -offline -demoSet" ``` -------------------------------- ### Sealed Trait Inheritance Example in Scala Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md An example of a sealed trait inheriting from multiple other traits, including those related to alignment and positioning. This pattern is used for complex type hierarchies. ```scala @js.native sealed trait center extends AlignSetting with CanvasTextAlign with LineAlignSetting with PositionAlignSetting with ScrollLogicalPosition ``` -------------------------------- ### Run Importer Demo Set Source: https://github.com/scalablytyped/converter/blob/master/docs/devel/about.md Execute the converter pipeline on the demo set of TypeScript code. This is a good command to run after changes to verify functionality. Review git changes after successful conversion. ```shell sbt:ScalablyTypedConverter> importer/runMain org.scalablytyped.converter.Main -softWrites -parseCache -offline -dontCleanProject -forceCommit -demoSet ``` -------------------------------- ### Run ScalablyTyped Converter in Development Mode Source: https://github.com/scalablytyped/converter/blob/master/CLAUDE.md Use this command to run the converter for a single library during development. Flags like -softWrites, -enableParseCache, and -offline can be adjusted as needed. ```bash sbt "importer/runMain org.scalablytyped.converter.Main -softWrites -enableParseCache -offline react" ``` -------------------------------- ### Accessing Extracted Literals Source: https://github.com/scalablytyped/converter/blob/master/docs/usage.md Concrete string, number, or boolean literals from source code are collected into objects for reuse. For example, string literals are found in `typings.react.reactStrings`. ```scala typings.react.reactStrings ``` -------------------------------- ### Configure NPM Dependencies Source: https://github.com/scalablytyped/converter/blob/master/docs/plugin.md Set up your project's npm dependencies within your `build.sbt` file. This includes both regular npm packages and their corresponding @types packages. ```scala project.settings( Compile / npmDependencies ++= Seq( "react-router-dom" -> "5.1.2", "@types/react-router-dom" -> "5.1.2" ) ) ``` -------------------------------- ### stc CLI Usage Source: https://github.com/scalablytyped/converter/blob/master/docs/cli.md Displays the available options for the stc command-line tool, including directory specification, dependency inclusion, flavour selection, Scala/Scala.js versions, and output package configuration. ```bash Usage: stc [options] [libs] -h, --help -v, --version -d, --directory Specify another directory instead of the current directory where your package.json and node_modules is --includeDev Include dev dependencies --includeProject When true (which is the default) uses scala-js-dom types when possible instead of types we translate from typescript in std -f, --flavour One of normal, japgolly, slinky, slinky-native. See https://scalablytyped.org/docs/flavour --scalajs Scala.js version --scala Scala version --outputPackage Libraries you want to enable @ScalaJSDefined traits for. -s, --stdlib Which parts of typescript stdlib you want to enable --organization Organization used (locally) publish artifacts --ignoredLibs Libraries you want to ignore libs Libraries you want to convert from node_modules ``` -------------------------------- ### Convert Local Typescript Project Source: https://github.com/scalablytyped/converter/blob/master/docs/cli.md Convert a local TypeScript project to Scala.js by building it with --declaration and running the CLI tool with --includeProject=true from the project directory. ```bash stc --includeProject=true ``` -------------------------------- ### Configure S3-Compatible Remote Cache Source: https://context7.com/scalablytyped/converter/llms.txt Set up remote caching using S3-compatible storage like DigitalOcean Spaces or MinIO. Configure the bucket, pull endpoint, and optionally credentials, region, and prefix. Push cache with `sbt stPublishCache`. ```scala // S3-compatible (DigitalOcean Spaces, MinIO, etc.) Global / stRemoteCache := RemoteCache.S3( bucket = "my-bucket", pull = "https://my-bucket.fra1.digitaloceanspaces.com/scalablytyped" ).withEndpoint("https://fra1.digitaloceanspaces.com") .withStaticCredentials("myAccessKey", "mySecretKey") .withRegion("eu-central-1") .withPrefix("scalablytyped") ``` -------------------------------- ### Set output package Source: https://github.com/scalablytyped/converter/blob/master/docs/conversion-options.md Use `stOutputPackage` to define the top-level package for all generated Scala code. ```scala project.settings( stOutputPackage := "org.awesome.sauce", ) ``` -------------------------------- ### Configure Rsync Remote Cache Source: https://github.com/scalablytyped/converter/blob/master/docs/remotecache.md Set up a remote cache using Rsync. This requires SSH access for pushing and an HTTP(S) endpoint for pulling. ```scala Global / stRemoteCache := RemoteCache.Rsync( push = "user@server.com:/path/to/st/cache", pull = new java.net.URI("https://server.com/path/to/st/cache") ) ``` -------------------------------- ### Run Importer Full Set Source: https://github.com/scalablytyped/converter/blob/master/docs/devel/about.md Execute the converter pipeline on the full set of TypeScript code. This process is time-consuming and recommended for larger changes. ```shell sbt:ScalablyTypedConverter> importer/runMain org.scalablytyped.converter.Main -softWrites -parseCache -offline -dontCleanProject -forceCommit ``` -------------------------------- ### Run Full ScalablyTyped Converter Conversion Source: https://github.com/scalablytyped/converter/blob/master/CLAUDE.md Initiates a full conversion process using the ScalablyTyped converter. This command includes flags for soft writes and enabling the parse cache. ```bash sbt "importer/runMain org.scalablytyped.converter.Main -softWrites -enableParseCache" ``` -------------------------------- ### Choose a Flavor for React Interop Source: https://context7.com/scalablytyped/converter/llms.txt Select one flavor per project to define how React libraries are wrapped. Slinky and Japgolly (scalajs-react) are common choices. Ensure npm dependencies are listed. ```scala lazy val slinkyApp = project .enablePlugins(ScalablyTypedConverterPlugin) .settings( stFlavour := Flavour.Slinky, // Slinky web // stFlavour := Flavour.SlinkyNative, // Slinky native // stFlavour := Flavour.Japgolly, // scalajs-react Compile / npmDependencies ++= Seq( "antd" -> "4.16.0" ) ) ``` -------------------------------- ### Accessing React Components Source: https://github.com/scalablytyped/converter/blob/master/docs/usage.md When using a React flavour, generated components are located in the `typings..components` package. This is the primary entry point for React-specific UI elements. ```scala typings..components ``` -------------------------------- ### Basic usage of Scala.js objects Source: https://github.com/scalablytyped/converter/blob/master/docs/objects.md Demonstrates constructing, mutating, duplicating, and combining JavaScript objects represented as Scala.js traits. Use `setX` for mutation and `duplicate.setX` for creating a modified copy. ```scala // At construction time we need to supply all required parameters val p = Point(x = 1,y = 2) // we can mutate what we have // this is equivalent to typescript `p.x = 3 val p2 = p.setX(3) // or we can duplicate and then mutate. // this is equivalent to typescript `const p2 = {...p, x: 3} val p3 = p.duplicate.setX(3) // we can combine with other javascript objects. // this is equivalent to javascript `const p3 = {...p, {}} val p4: Point with TickOptions = p.combineWith(TickOptions()) // fallback, if the type definitions are wrong or for any other reason you can break the contract val p5: p.duplicate.set("x", "foo") // you can also set any other property val p6: p.duplicate.set("x2", "foo") ``` -------------------------------- ### Customize Output Package Source: https://context7.com/scalablytyped/converter/llms.txt Override the default `typings` top-level package with `stOutputPackage`. This is necessary when shading multiple conversions into the same build. Optionally, use `stPrivateWithin` to make generated code package-private. ```scala project.settings( stOutputPackage := "org.mycompany.facades", // Generated code: org.mycompany.facades.react.mod.createElement(...) ) // If making generated code package-private: project.settings( stOutputPackage := "mylib.internal.facades", stPrivateWithin := Some("internal") ) ``` -------------------------------- ### Enable SBT Converter Plugin Source: https://github.com/scalablytyped/converter/blob/master/docs/plugin.md Activate the ScalablyTypedConverterPlugin for a specific project in your `build.sbt` file. ```sbt project.enablePlugins(ScalablyTypedConverterPlugin) ``` -------------------------------- ### Ignore a module prefix Source: https://github.com/scalablytyped/converter/blob/master/docs/conversion-options.md Use `stIgnore` with `++=` to exclude modules matching a prefix. This is helpful for large libraries where only a subset of modules is required. ```scala project.settings( stIgnore ++= List("material-ui/svg-icons") ) ``` -------------------------------- ### TypeScript Import to ScalablyTyped Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md Demonstrates how a TypeScript import statement is translated into its ScalablyTyped equivalent, showing the package naming hierarchy. ```typescript import AnchorLong from "antd/es/anchor/AnchorLink"; ``` ```scala import typings.antd.esAnchorAnchorLinkMod.{default => AnchorLong} ``` -------------------------------- ### Minimize Libraries with Selection Source: https://github.com/scalablytyped/converter/blob/master/docs/library-developer.md Use `stMinimize` with `Selection.AllExcept` to remove transitive dependencies, keeping only specified libraries. This is useful for managing large dependency trees. ```scala project.settings( Compile / stMinimize := Selection.AllExcept("axios", "material-ui", "mobx-react", "mobx") ) ``` -------------------------------- ### Configure AWS S3 Remote Cache Source: https://github.com/scalablytyped/converter/blob/master/docs/remotecache.md Set up a remote cache using AWS S3. Credentials are automatically picked up from standard AWS locations. ```scala Global / stRemoteCache := RemoteCache.S3Aws( bucket = "scalablytyped-demos", region = "eu-central-1", prefix = Some("st-cache") ) ``` -------------------------------- ### Converting a Local TypeScript Project Source: https://context7.com/scalablytyped/converter/llms.txt Generate Scala.js bindings for your own TypeScript project by running stc with the --includeProject flag after building your TS project. ```bash # 1. Build your TS project to emit .d.ts files tsc --declaration --emitDeclarationOnly # 2. Run stc from your project root with --includeProject stc --includeProject=true # ScalablyTyped uses the current directory name as the library name. # The generated Scala package will be: typings. # In your webpack config, add an alias so bundler finds the sources: # resolve: { alias: { 'my-ts-lib': path.resolve(__dirname, 'dist') } } ``` -------------------------------- ### Configure Rsync Remote Cache Source: https://context7.com/scalablytyped/converter/llms.txt Use Rsync for remote caching, requiring SSH key access for pushing and HTTP for pulling. Configure the push destination and pull URI. Cache is pushed with `sbt stPublishCache`. ```scala // Rsync (requires ssh key access for push, http for pull) Global / stRemoteCache := RemoteCache.Rsync( push = "user@server.com:/var/www/st-cache", pull = new java.net.URI("https://server.com/st-cache") ) ``` -------------------------------- ### Instantiate Scala.js Object with Properties Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md Demonstrates creating a new Scala.js object instance with specific properties. This is the default encoding for user-created types extending `js.Object`. ```scala new Props { override val foo = 1 } ``` -------------------------------- ### Keep Specific Elements with stMinimizeKeep Source: https://github.com/scalablytyped/converter/blob/master/docs/library-developer.md Configure `stMinimize` to `Selection.All` and then use `stMinimizeKeep` to specify individual elements to retain. The names provided should match the generated Scala code without the `typings` prefix. ```scala project.settings( /* setup libraries */ Compile / npmDependencies ++= Seq( "moment" -> "2.24.0", "react-big-calendar" -> "0.22", "@types/react-big-calendar" -> "0.22.3" ), /* say we want to minimize all */ stMinimize := Selection.All, /* but keep these very specific things*/ stMinimizeKeep ++= List( "moment.mod.^", "reactBigCalendar.mod.momentLocalizer", "reactBigCalendar.mod.View", ), ) ``` -------------------------------- ### CLI Tool Usage Source: https://context7.com/scalablytyped/converter/llms.txt The stc command-line tool converts TypeScript definitions without sbt. Run it in a project directory with package.json and node_modules. ```bash # Install via Coursier cs install stc # Run in your project directory (converts all deps from package.json) stc # Specify a different directory stc -d /path/to/my/js-project # Convert only specific libraries stc react lodash # Full option reference: # -d, --directory directory with package.json and node_modules # --includeDev include devDependencies # --includeProject include the project's own TypeScript sources # -f, --flavour normal | japgolly | slinky | slinky-native # --scalajs Scala.js version # --scala Scala version # --outputPackage top-level package for generated code (default: typings) # --enableScalaJSDefined libs to enable @ScalaJSDefined traits # -s, --stdlib TypeScript stdlib parts to include # --organization organization for locally published artifacts # --ignoredLibs libraries to skip during conversion stc --flavour slinky --stdlib es6 --outputPackage myfacades react lodash ``` -------------------------------- ### Ignore Problematic Libraries Source: https://context7.com/scalablytyped/converter/llms.txt Use `stIgnore` to skip transitive dependencies that are problematic or unused. Ignored types are replaced with `js.Any` and a comment. ```scala project.settings( // Exclude a whole library (e.g., skip heavy CSS type definitions) stIgnore += "csstype", // Exclude a module prefix (e.g., skip all material-ui icon components) stIgnore ++= List("material-ui/svg-icons") ) ``` -------------------------------- ### Choose Slinky Flavour Source: https://github.com/scalablytyped/converter/blob/master/docs/plugin.md Configure the plugin to use the Slinky flavour for either web or native projects by setting the `stFlavour` setting in your `build.sbt`. ```scala project.settings( // for Slinky web projects stFlavour := Flavour.Slinky, // for Slinky native projects stFlavour := Flavour.SlinkyNative, ) ``` -------------------------------- ### ScalablyTyped Build Tuning Options Source: https://context7.com/scalablytyped/converter/llms.txt Configuration options for the ScalablyTyped converter to control output verbosity, cache directory, dependency inclusion, and DOM API usage. ```scala // Suppress verbose converter output Global / stQuiet := true // Change cache directory (default: ~/.cache/scalablytyped) Global / stDir := file("/fast-ssd/st-cache") // Include devDependencies in conversion stIncludeDev := true // Use scala-js-dom types for DOM APIs (default: true) stUseScalaJsDom := false // use TypeScript's own std lib instead ``` -------------------------------- ### Manual source generation mode Source: https://github.com/scalablytyped/converter/blob/master/docs/library-developer.md Configure the plugin to generate source files manually when `stImport` is run, specifying the output directory and optional overrides. ```scala stSourceGenMode := SourceGenMode.Manual(toDir: File, toDirOverrides: Map[String, File] = Map.empty) ``` -------------------------------- ### Choose Scalajs-react Flavour Source: https://github.com/scalablytyped/converter/blob/master/docs/plugin.md Configure the plugin to use the Japgolly flavour for Scalajs-react projects by setting the `stFlavour` setting in your `build.sbt`. ```scala project.settings( stFlavour := Flavour.Japgolly ) ``` -------------------------------- ### Importing from Generated Library Modules in Scala.js Source: https://context7.com/scalablytyped/converter/llms.txt Shows common import patterns for accessing generated Scala.js types from various parts of a library. Includes standard modules, named sub-modules, React components, string literals, global access, and side-effect modules. ```scala // Standard module import (most common entry point) import typings.react.mod._ import typings.antd.mod.Button // Named sub-module import import typings.react.experimentalMod._ // React components (with a flavour) import typings.antd.components.Button import typings.antd.components.Input // String literals for type-safe APIs import typings.std.stdStrings.{`2d`, webgl} val ctx2d = canvas.getContext_2d(`2d`) val ctxWgl = canvas.getContext_webgl(webgl) // Global-namespace access import typings.std.global._ typings.std.^.onerror = (msg, _, _, _, _) => typings.std.console.warn(msg) // Module side-effect load (jquery-ui style monkey-patching) typings.jqueryui.jqueryuiRequire val jqui = typings.jquery.JQuery.asInstanceOf[typings.jqueryui.JQuery] // Instantiable types (JS newable patterns) val blob: Blob = typings.std.window.Blob.newInstance0() val blobWithData: Blob = typings.std.window.Blob.newInstance1(js.Array("hello")) // TS import: import AnchorLong from "antd/es/anchor/AnchorLink" // Scala equivalent: import typings.antd.esAnchorAnchorLinkMod.{default => AnchorLong} ``` -------------------------------- ### Select TypeScript Standard Libraries Source: https://context7.com/scalablytyped/converter/llms.txt Configure `stStdlib` to mirror TypeScript's `--lib` compiler option, restricting included DOM/JS APIs. This is useful for Node.js apps or targeting specific ECMAScript versions. ```scala project.settings( // Node.js app — no DOM APIs stStdlib := List("es2019"), // Browser app with async generators stStdlib := List("es6", "es2018.asyncgenerator"), // Full modern browser (default-ish) stStdlib := List("es5", "dom", "dom.iterable", "es2015.collection") ) ``` -------------------------------- ### Publish Remote Cache Source: https://context7.com/scalablytyped/converter/llms.txt Manually publish the compiled cache artifacts to the configured remote storage using the `stPublishCache` command in the sbt shell or CI. ```scala // Publish cache from sbt shell or CI // sbt stPublishCache ``` -------------------------------- ### Configure S3-Compatible Remote Cache Source: https://github.com/scalablytyped/converter/blob/master/docs/remotecache.md Configure a remote cache for S3-compatible storage services. You must provide the pull URI and can optionally set an endpoint, credentials, region, and prefix. ```scala Global / stRemoteCache := RemoteCache.S3( bucket = "my-bucket", pull = "https://my-bucket.https://fra1.digitaloceanspaces.com/scalablytyped" ).withEndpoint("https://fra1.digitaloceanspaces.com") .withStaticCredentials("myAccessKey", "mySecretKey") .withRegion("eu-central-1") .withPrefix("scalablytyped") ``` -------------------------------- ### EventTarget addEventListener Overloads Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md Demonstrates various overloads for the addEventListener method on EventTarget, handling different listener types and options. ```scala def addEventListener(`type`: String, listener: EventListenerOrEventListenerObject, options: Boolean): Unit = js.native def addEventListener(`type`: String, listener: Null, options: AddEventListenerOptions): Unit = js.native def addEventListener(`type`: String, listener: Null, options: Boolean): Unit = js.native ``` -------------------------------- ### Configure AWS S3 Remote Cache Source: https://context7.com/scalablytyped/converter/llms.txt Distribute compiled artifacts via S3 for team and CI builds. Use `stRemoteCache` to configure the S3 bucket, region, and an optional prefix. Push the cache using `sbt stPublishCache`. ```scala // AWS S3 Global / stRemoteCache := RemoteCache.S3Aws( bucket = "my-st-cache-bucket", region = "eu-central-1", prefix = Some("st-cache") ) ``` -------------------------------- ### Add SBT Converter Plugin Source: https://github.com/scalablytyped/converter/blob/master/docs/plugin.md Add the ScalablyTyped converter plugin to your SBT build by including this line in your `project/plugins.sbt` file. ```sbt addSbtPlugin("org.scalablytyped.converter" % "sbt-converter" % "@VERSION@") ``` -------------------------------- ### Enable ScalablyTypedConverterExternalNpmPlugin Source: https://github.com/scalablytyped/converter/blob/master/docs/plugin-no-bundler.md Enable the ScalablyTypedConverterExternalNpmPlugin in your SBT project. This is necessary when not using scalajs-bundler. ```scala project.enablePlugins(ScalablyTypedConverterExternalNpmPlugin) ``` -------------------------------- ### SBT Plugin with scalajs-bundler Source: https://context7.com/scalablytyped/converter/llms.txt Integrate ScalablyTyped using the sbt plugin and scalajs-bundler. Declare npm dependencies in build.sbt; the converter runs automatically on compile. ```scala // project/plugins.sbt addSbtPlugin("org.scalablytyped.converter" % "sbt-converter" % "1.0.0-beta44") // build.sbt lazy val app = project .enablePlugins(ScalablyTypedConverterPlugin) .settings( scalaVersion := "3.2.2", scalaJSUseMainModuleInitializer := true, Compile / npmDependencies ++= Seq( "react" -> "17.0.2", "@types/react" -> "17.0.38", "react-dom" -> "17.0.2", "@types/react-dom" -> "17.0.11" ), useYarn := true // faster dependency resolution ) ``` -------------------------------- ### Run Importer Unit Tests Source: https://github.com/scalablytyped/converter/blob/master/docs/devel/about.md Execute unit tests specifically for the TypeScript parser. Ensure all parser changes are accompanied by corresponding unit tests. ```shell sbt importer/testOnly org.scalablytyped.converter.internal.ts.parser.* ``` -------------------------------- ### Activate ScalablyTypedConverterGenSourcePlugin Source: https://github.com/scalablytyped/converter/blob/master/docs/library-developer.md Enable the ScalablyTyped converter plugin for a specific project in your build.sbt file. ```scala project.enablePlugins(ScalablyTypedConverterGenSourcePlugin) ``` -------------------------------- ### Accessing Global Namespaces Source: https://github.com/scalablytyped/converter/blob/master/docs/usage.md Global references for libraries like std, node, or electron are accessible through `typings..global`. A trailing underscore may be present to handle name clashes. ```scala typings..global ``` -------------------------------- ### Enable tree shaking for React components Source: https://github.com/scalablytyped/converter/blob/master/docs/conversion-options.md Use `stReactEnableTreeShaking` to configure React flavors to prefer components from long module paths over short ones. This can significantly reduce bundle sizes. ```scala project.settings( stReactEnableTreeShaking := Selection.NoneExcept("office-ui-fabric-react") ) ``` -------------------------------- ### SBT Plugin without scalajs-bundler (External NPM) Source: https://context7.com/scalablytyped/converter/llms.txt Use ScalablyTypedConverterExternalNpmPlugin when managing node_modules externally. Implement the externalNpm task to point to your node_modules directory. ```scala import scala.sys.process._ lazy val app = project .enablePlugins(ScalablyTypedConverterExternalNpmPlugin) .settings( scalaVersion := "3.2.2", externalNpm := { Process("yarn", baseDirectory.value).! baseDirectory.value // directory with package.json + node_modules }, Compile / npmDependencies ++= Seq( "react" -> "17.0.2", "@types/react" -> "17.0.38" ) ) ``` -------------------------------- ### Enable Quiet Mode for Scala Source: https://github.com/scalablytyped/converter/blob/master/docs/conversion-options.md Set `stQuiet` to `true` to suppress debug output during the conversion process, making the build logs cleaner. ```scala Global / stQuiet := true ``` -------------------------------- ### MediaStream addEventListener Overloads for 'addtrack' event Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md Illustrates specific addEventListener overloads for the 'addtrack' event on MediaStream, maintaining type safety for the listener. ```scala @JSName("addEventListener") def addEventListener_addtrack(`type`: addtrack, listener: js.ThisFunction1[/* this */ this.type, /* ev */ MediaStreamTrackEvent, _]): Unit = js.native @JSName("addEventListener") def addEventListener_addtrack(`type`: addtrack, listener: js.ThisFunction1[/* this */ this.type, /* ev */ MediaStreamTrackEvent, _], options: AddEventListenerOptions): Unit = js.native @JSName("addEventListener") def addEventListener_addtrack(`type`: addtrack, listener: js.ThisFunction1[/* this */ this.type, /* ev */ MediaStreamTrackEvent, _], options: Boolean): Unit = js.native ``` -------------------------------- ### Ignore a specific module Source: https://github.com/scalablytyped/converter/blob/master/docs/conversion-options.md Use `stIgnore` to exclude a specific module from conversion. This is useful for dependencies that fail to compile or are not needed. References to ignored modules will be translated as `js.Any`. ```scala project.settings( stIgnore += "csstype" ) ``` -------------------------------- ### Specify Custom Cache Directory for Scala Source: https://github.com/scalablytyped/converter/blob/master/docs/conversion-options.md Use `stDir` to define a custom directory for storing caches and build artifacts, overriding the default OS-specific location. ```scala Global / stDir := file("/some/other/dir") ``` -------------------------------- ### TypeScript Type Mappings: Partial, Pick, Record Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md Illustrates TypeScript's type mapping utility types. These are used for transforming object types, such as making properties optional or selecting specific properties. ```typescript // from typescript's bundled definitions /** * Make all properties in T optional */ type Partial = { [P in keyof T]?: T[P]; }; /** * From T pick a set of properties K */ type Pick = { [P in K]: T[P]; }; /** * Construct a type with a set of properties K of type T */ type Record = { [P in K]: T; }; ``` -------------------------------- ### Constructing and Mutating Generated Objects in Scala.js Source: https://context7.com/scalablytyped/converter/llms.txt Demonstrates creating and modifying JavaScript objects from TypeScript interfaces using generated Scala.js code. Covers construction, mutation, duplication, combining objects, and handling optional/nullable members. ```scala // Generated trait (from TS: interface Point { x: number; y: number }) // typings.mylib.mod.Point import typings.mylib.mod.Point // Construct with all required fields val p = Point(x = 1.0, y = 2.0) // Mutate a field (equivalent to TS: p.x = 3) val p2 = p.setX(3.0) // Duplicate then mutate (equivalent to TS: const p2 = {...p, x: 3}) val p3 = p.duplicate.setX(3.0) // Combine two JS objects (equivalent to JS: {...p, ...tickOptions}) val p4: Point with TickOptions = p.combineWith(TickOptions()) // Raw property escape hatch val p5 = p.duplicate.set("x", "overrideWithAnything") // Optional/nullable members — various setters generated automatically: // .setBUndefined, .setCNull, .setDNull, .setDUndefined val n = Nullability(a = 42.0) .setB(3.14) .setC(0.0) .setDNull // Union-type members — overloads generated per concrete type: // .setAFunction1(fn) converts Scala function to JS function Complex().setAFunction1(n => println(n)) // Inheritance: parent setters work on child types without losing the child type val c = Child[Int, String](t = 1) val c2 = c.setT2("foo") // Child-specific setter val c3: Child[Int, String] = c.setT(42) // Parent setter, preserves Child type // Discriminated union / literal types import typings.mylib.mod.{Branch, Leaf, Tree} val tree1 = Branch(left = Leaf(1), right = Leaf(2)) // or via the union type's companion: val tree2 = Tree.Branch(Tree.Leaf(1), Tree.Leaf(1)) ``` -------------------------------- ### Exclude Javadocs for Facade Libraries Source: https://github.com/scalablytyped/converter/blob/master/docs/library-developer.md When packaging a facade generated from ScalablyTyped without custom code, exclude javadocs to reduce artifact size. This is often required by artifact repositories like Sonatype. ```scala sources in (Compile, doc) := Nil, ``` -------------------------------- ### Scala EventTarget addEventListener Overloads Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md Scala encoding for EventTarget's addEventListener, demonstrating how overloads are duplicated to handle different parameter combinations and potential nullability differences. ```scala @js.native trait EventTarget extends js.Object { def addEventListener(`type`: String): Unit = js.native def addEventListener(`type`: String, listener: EventListenerOrEventListenerObject): Unit = js.native def addEventListener(`type`: String, listener: EventListenerOrEventListenerObject, options: AddEventListenerOptions): Unit = js.native } ``` -------------------------------- ### Set Scalajs-react flavour Source: https://github.com/scalablytyped/converter/blob/master/docs/library-developer.md Configure the ScalablyTyped converter to use the Japgolly flavour for scalajs-react projects. ```scala project.settings( stFlavour := Flavour.Japgolly ) ``` -------------------------------- ### Casting to ArrayLike Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md Shows how to cast a standard Scala.js Array to an ArrayLike trait when the compiler cannot infer the subtyping relationship. ```scala typings.std.Array(1).asInstanceOf[ArrayLike[Int]] ``` -------------------------------- ### Handling Top-Level Members with '^' Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md Illustrates how to reference module objects or mutate top-level members using the '^' object, which represents the module itself in ScalablyTyped. ```scala new typings.node.eventsMod.^() ``` ```scala typings.std.^.onerror = (x, _, _, _, _) => typings.std.console.warn(x) ``` -------------------------------- ### Set Slinky flavour Source: https://github.com/scalablytyped/converter/blob/master/docs/library-developer.md Configure the ScalablyTyped converter to use the Slinky flavour for web or native projects. ```scala project.settings( // for Slinky web projects stFlavour := Flavour.Slinky, // for Slinky native projects stFlavour := Flavour.SlinkyNative, ) ``` -------------------------------- ### Scala Consolidated getContext Method Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md A consolidated Scala representation of the HTMLCanvasElement getContext method, sacrificing type-safety for simplicity. ```scala @js.native trait HTMLCanvasElement extends HTMLElement { // we don't actually do this def getContext(contextId: String, contextAttributes: js.UndefOr[js.Object | CanvasRenderingContext2DSettings | WebGLContextAttributes]): CanvasRenderingContext2D | WebGLRenderingContext | Null = js.native } ``` -------------------------------- ### Fallback Encoding for Unsupported Type Mappings in Scala Source: https://github.com/scalablytyped/converter/blob/master/docs/encoding.md Illustrates the fallback mechanism for type mappings that cannot be fully translated to Scala.js. The transformation is kept as a comment, and a type alias is used. ```scala type Partial[T] = /* import warning: ImportType.apply c Unsupported type mapping: {[ P in keyof T ]:? T[P]} */ typings.std.stdStrings.Partial with T ``` -------------------------------- ### Approximating Type Mappings in Scala Source: https://context7.com/scalablytyped/converter/llms.txt When direct type mappings are not available, use `js.Dynamic.literal` and `asInstanceOf` to approximate types like `Partial`. This is useful for dynamic object creation. ```scala // Type mappings fallback (Partial etc. may be approximated) val partialPerson: typings.std.Partial[Person] = js.Dynamic.literal(name = "Alice").asInstanceOf[typings.std.Partial[Person]] ``` -------------------------------- ### Constructing objects with optional/nullable members Source: https://github.com/scalablytyped/converter/blob/master/docs/objects.md Construct a `Nullability` object by providing required members and then chaining setters for optional and nullable members. Use `setDNull` or `setDUndefined` to explicitly set null or undefined values. ```scala Nullability(a = 1) .setB(2) .setC(3) .setDNull ``` -------------------------------- ### Scala.js Typed Inheritance with Type Parameters Source: https://github.com/scalablytyped/converter/blob/master/docs/objects.md Demonstrates inheritance between traits with type parameters. The `Child` trait extends `Parent`, allowing setters from both traits to be used on child objects while preserving type information. ```scala @js.native trait Parent[T] extends StObject { var t: T = js.native } object Parent { @scala.inline def apply[T](t: T): Parent[T] = { val __obj = js.Dynamic.literal(t = t.asInstanceOf[js.Any]) __obj.asInstanceOf[Parent[T]] } @scala.inline implicit class ParentMutableBuilder[Self <: Parent[_], T] (val x: Self with Parent[T]) extends AnyVal { @scala.inline def setT(value: T): Self = StObject.set(x, "t", value.asInstanceOf[js.Any]) } } @js.native trait Child[T1, T2] extends Parent[T1] { var t2: js.UndefOr[T2] = js.native } object Child { @scala.inline def apply[T1, T2](t: T1): Child[T1, T2] = { val __obj = js.Dynamic.literal(t = t.asInstanceOf[js.Any]) __obj.asInstanceOf[Child[T1, T2]] } @scala.inline implicit class ChildMutableBuilder[Self <: Child[_, _], T1, T2] (val x: Self with (Child[T1, T2])) extends AnyVal { @scala.inline def setT2(value: T2): Self = StObject.set(x, "t2", value.asInstanceOf[js.Any]) @scala.inline def setT2Undefined: Self = StObject.set(x, "t2", js.undefined) } } ``` ```scala val c = Child[Int, String](1) val c2 = c.setT2("foo") val c3: Child[Int, String] = c.setT(1) ``` -------------------------------- ### Configure ScalablyTyped Flavour in sbt Source: https://github.com/scalablytyped/converter/blob/master/docs/flavour.md Specify the desired React wrapper flavour in your sbt build settings. Options include Slinky, SlinkyNative, and ScalajsReact. ```scala project.settings( // for Slinky web projects stFlavour := Flavour.Slinky, // for Slinky native projects stFlavour := Flavour.SlinkyNative, // for scalajs-react projects stFlavour := Flavour.ScalajsReact ) ```