Error encountered: firebase is not defined within a Kotlin/JS project utilizing Dukat generated declarations

As part of my kotlin js project, I brought in the firebase dependency. Leveraging Dukat, I obtained access to the type references and successfully compiled them. While my Kotlin code compiles without any issues, it appears that the webpack bundle does not include the firebase library as expected.

Here's what I did :

  • Installed firebase (npm install firebase)
  • Utilized Dukat to generate declarations (
    dukat firebase/app/dist/app/index.d.ts
    ).
  • Copied the generated files into my Kotlin JS project.

https://i.sstatic.net/YOgjl.png

After making some modifications, my Kotlin code compiles smoothly. However, upon running the code, a

Uncaught ReferenceError: firebase is not defined error
surfaces on the frontend. This error occurs prior to the execution of any firebase-related code, indicating a potential bundling issue.

Below is the stacktrace:

sample-firebase.js:391 Uncaught Error: Cannot find module 'firebase'
    at webpackMissingModule (sample-firebase.js:3)
    at eval (sample-firebase.js:3)
    at eval (sample-firebase.js:8)
    at Object../kotlin-dce-dev/sample-firebase.js (sample-firebase.js:359)
    at __webpack_require__ (sample-firebase.js:388)
    at sample-firebase.js:1447
    at sample-firebase.js:1450
    at webpackUniversalModuleDefinition (sample-firebase.js:17)
    at sample-firebase.js:18
[webpack-dev-server] Module not found: Error: Package path . is not exported from package /Users/julien/Developer/kotlin-samples/sample-firebase/build/js/node_modules/firebase (see exports field in /Users/julien/Developer/kotlin-samples/sample-firebase/build/js/node_modules/firebase/package.json)

Examining my Client code reveals that the issue arises in the line containing initializeApp.

fun main() {
    val firebaseConfig: Json = json(...)

    val fire = initializeApp(firebaseConfig)
    console.log(fire)
    window.onload = {
        console.log(sorted(arrayOf(1, 2, 3)))
        startFirebase();
        document.body?.sayHello() } }

The error vanishes when I remove all firebase-related code, but this also eliminates firebase functionalities.

You can access my client code here. To replicate the issue, simply run ./gradlew run in the sample-firebase module.

I have attempted various solutions:

  • Initially, Dukat was generating package names for the Kotlin declarations. Removing these changes did not impact the error.
  • Directly importing firebase from my Client (`require("firebase")) failed to bundle it.
  • Additionally, declaring an implementation dependency to another npm package and using homemade declarations following the instructions in the documentation proved successful.
  • The runtime import issue before the javascript execution points towards a problem with the bundle.

What steps can be taken to identify the disparity between my error-free Kotlin declarations and the failed import of firebase on the frontend?

Answer №1

Dukat is still in the experimental phase, so it's best to use a handmade wrapper like the one shown below:

external interface FirebaseConfig{
}

external interface AppSettings{
    var settingValue: String  // required settings
}

external interface FirestoreApp{
}

@JsModule("firebase/firestore")
@JsNonModule
external val firestoreModule: dynamic

val initializeFirestoreApp: (config: FirebaseConfig, settings: AppSettings) -> FirestoreApp = firestoreModule.initializeApp

Add this to your build.gradle file:

implementation(npm("firebase", "9.1.3"))

Then you can use it as follows:

fun main() {
    val config: dynamic = object {}
    val settings: dynamic = object {}
    settings["settingValue"] = "12345"
    val firestoreApp = initializeFirestoreApp(
        config.unsafeCast<FirebaseConfig>(),
        settings.unsafeCast<AppSettings>()
    )
    console.log(firestoreApp)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing an issue with type error when transitioning syntax from using require to import

After transitioning from require in CommonJS syntax to import in ES Module syntax, I encountered an error. I decided to develop a todo-app using Node.js, TypeScript, and MySQL. To start off, I wrote the initial code snippets below: // db.ts export {}; co ...

Exploring techniques to compare two objects in JavaScript and then dynamically generate a new object with distinct values

var person1={ name:"Sarah", age:"35", jobTitle:"Manager" } var person2={ name:"Sarah Sanders", age:"35", jobTitle:"Manager" } //the name value has been updated in the above object, s ...

Application freezes during initialization of Here Maps Engine within a nested fragment

Utilizing HereMaps within a child fragment inside a ViewPager2 causes the app to momentarily freeze as the map initializes. Only after the map has finished initializing can I interact with the UI. In my project, an Activity sets up the page adapters, wher ...

The ultimate guide to passing slots from Parent to Child Components seamlessly using PrimeVue

As I venture into creating my own component library by wrapping some PrimeVue components, I am faced with the challenge of handling numerous slots. Many PrimeVue components come with a large number of slots, and passing each one individually seems like a ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

The tslint exclusion is not functioning properly for tsoa endpoints

I'm trying to remove the routes.ts file generated by tsoa routes from being compiled by tslint. I've used the exclude option but it doesn't seem to be working specifically for routes.ts. The exclude option works for other files, except for r ...

Transforming jQuery library functions into TypeScript syntax

I have developed a directive using TypeScript. Here is an example of the code: 'use strict'; module App.Directives { interface IPageModal extends ng.IDirective { } interface IPageModalScope extends ng.IScope { //modal: any ...

Rxjs: accessing the most recent value emitted by an observable

As shown in the demo and indicated by the title const { combineLatest, interval, of } = rxjs; const { first, last, sample, take, withLatestFrom } = rxjs.operators; const numbers = interval(1000); const takeFourNumbers = numbers.pipe(take(4)); takeFourNu ...

What is the best way to transfer the selected value from a dropdown to another component in React?

I am working on a select component where the values are fetched from useEffect data. When I select a value, I can see it in the console. const SelectName = () => { const [value, setValue] = useState(0); const [names, setNames] = useState([]); cons ...

Angular integration problem with aws-amplify when signing up with Google account

I am attempting to integrate AWS-Amplify(^4.3.0) with angular-12 and typescript (4.3.5). I have followed the documentation to configure amplify properly, but when trying to start the app, I encountered some amplify errors as shown below. Warning: D:\G ...

Retrieve values from a multi-level nested object by using square bracket notation for each level

I am in need of a config object to display nested data. Check out the demo code for reference In the code, accessing "customer.something" is essential. There can be multiple levels of nesting, which the grid handles with field='customer.som ...

The data retrieved using Ionic 3 Angular Fire's payload.val() seems to be returning

Is it possible to determine whether a profile is filled in or empty when using Firebase Database for storing profile information? Currently, I am utilizing profile.payload.val(), but it seems to return null in both cases instead of true when the profile is ...

Exploring the intricacies of the top-level get() function in Kotlin

While I was browsing through the repository on dagger usage in android with kotlin, I came across the application class: class ConnectingTheDotsApp : Application() { val appComponent: AppComponent by lazy { DaggerAppComponent .fact ...

Create a TypeScript interface that represents an object type

I have a Data Structure, and I am looking to create an interface for it. This is how it looks: const TransitReport: { title: string; client: string; data: { overdueReviews: number; outstandingCovenantBreaches ...

"Utilizing Ionic 3 for navigating internal links within a website using the tag

Hello everyone, I recently started exploring Ionic and Angular and I have a question regarding internal links in the Ionic framework. To begin my learning journey, I decided to work with the pre-made project called Ionic sidemenu. I am attempting to create ...

Setting up subdocuments using Typegoose to initialize models

We recently switched our project from pure Mongoose to Typegoose, and while we are satisfied overall, there is one issue that continues to trouble us. Consider the following simple model: class Animal { @prop() public name?: string; } const AnimalMode ...

Retrieve and showcase data using Ionic 2's local storage functionality

Hi, I'm having trouble accessing my data in local storage. Every time I try, it gives me an error. I need assistance with displaying my data at home. Thank you for your help :) Error: Typescript Error Argument of type 'Promise' is not assi ...

Organize multiline string based on regex pattern using Javascript

I need to split a multi-line string and group it by a specific regex pattern that repeats throughout the text Some random filler in the beginning of the content Checking against xyz... Text goes here More text and more. Checking against abc... Another se ...

Loss of TypeScript's generic types within arrays

I am currently attempting to obtain an instance of a Sequence class that contains an array of various Request objects, each following the same pattern. Each Request object consists of an operation property (a string) and a property with the value of the re ...

Verifying currency in mat-input field

I need help implementing validation for inputting prices on a form. For example, if a user types in $20.0000, I want a validation message to appear marking the input as invalid. Would this type of validation require regex, and if so, how would I go about ...