Using Firebase with Webpack and TypeScript - javascript

I'm trying to pull some data from a Firebase instance, but am running into an issue when trying to bind it to a variable. I'm using TypeScript and Webpack to build.
main.ts
import * as Firebase from 'firebase';
class filter {
constructor(){
let ref = new Firebase('my-url-here');
}
}
The typings and npm module are installed and working, and Visual Code brings up no errors, but when I hit the browser I get:
ERROR
TypeError: Firebase is not a constructor
..
Logging Firebase to the console returns an object with methods like auth, app and database, but none of these seem to work either (or I'm calling them incorrectly). Any ideas?
A general best practice on how to incorporate Firebase into a Webpack/TypeScript would be just as welcome.

In my project i had the same error: It was caused by the firebase.json file which i guess got picked up by webpack.
As i can only guess why it happened: Webpack creating a symbol "Firebase" which replaced the constructor of firebase itself.
Have you done a firebase init in your directory?
Also see : https://github.com/angular/angularfire2/issues/187

Related

How can I use Firebase 9.x + Flow

I'm working on a NextJS project using Flow and I'm trying to import Firebase latest version 9.1.3, but when I try to use it, Flow complains that cannot find the module.
// Error: Cannot resolve module `firebase/app`.Flow(cannot-resolve-module)
import { initializeApp, getApps } from 'firebase/app';
import { getAnalytics } from 'firebase/analytics';
I only found an old solution on flow-typed for Firebase 5.x.x, but API has changed since then, and manually writing a Library Definition is super time consuming.
I noticed that Firebase uses Typescript, is there a way I can import/convert to use Flow?
No flow types and TS types are not compatible although they achieve the same goal they are different in their typing philosophy.
Regarding firebase types, because firebase doesn't use flow, flow-typed is the correct place to retrieve them if the existed but no one has done so for firebase types for a while.
I have personally made a start in a project I started a while back but you may need to add more to suit your usecase (firebase types in my project). If these suit your usecase as a base I'm happy to commit them into flow-typed but I'll just need to include some tests.

'Firebase Not Defined' An Answer For Version 9 Of Firebase

Im trying to make a database call/post but im getting the error
functions.js:7 Uncaught ReferenceError: firebase is not defined
From my research it is my understanding that 'firebase' is defined in the firebase.js script file that is imported using the CDN code from the setting panel in Firebase..
But all the help pages i find are from 2014-2017 and version 9 of Firebase uses a completely different import language.. These pages are no help to me..
I am using the standard
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
Am I right in thinking that because this import is happening (and its seemingly is - firebase-app.js is showing up in the inspector) That firebase should be defined...
Or is firebase defined somewhere else and im missing something??
If this is the case where is firebase defined and how do i import it (with V9 Firebase)
Thanks
Edit: Im doing this all through a tutorial I found on Youtube, its from 2019.. Is it possible that calling upon 'firebase' now is outmoded and that is what I am having these troubles? Or should i expect it to work and keep trying to find a solution?
In v8 and older versions of the Firebase Web SDK, now referred to as the "namespaced SDK", the SDK would add methods and types to a global object called firebase. You will see a lot of existing tutorials with code that looks like firebase.initializeApp(), firebase.database() and firebase.firestore.FieldValue.increment(). All of these calls will not work in the newer versions of the Firebase Web SDK.
In v9 and later versions of the Firebase Web SDK, now referred to as the "modular SDK", the SDK undertook a major architectural revamp and introduced lots of breaking changes. The primary change with the new version is that the firebase global object was completely removed and every method and type is now exported independently. When using this new SDK with a build tool like Webpack or Rollup, it can "shake the tree" to loosen and remove all of the bits of code that you don't actually use in your code from the final build.
As an example, if you don't use any of the FieldValue transforms in your code (like increment(), serverTimestamp() and arrayUnion()) they won't be included in your final build saving you and your users resources and time.
Not sure how you are using the script files, but have u defined them as "modules" in you html like:
and have you initialized firebase from your app:
const firebaseConfig = {
YOU_FIREBASE_CONFIG
}
const app = initializeApp(firebaseConfig)
The difference between v8 and v9 of firebase is a well-known error these days.
I am not sure this could be the exact solution, but at least as a hint.
Using compat is a way to solve.
Based in the firebase document below.
import firebase from 'firebase/compat/app';
↑would be how to import.....
Upgrade from version 8 to the modular Web SDK
When you run this code:
import { initializeApp } from ...
This code imports only the initializeApp function, and nothing else. That's precisely its point, because by using these very granular imports, bundler tools (like webpack) are able to drop any part of the Firebase SDK that you are not using from their output, resulting in a significantly smaller app.
So when you run that import, there is no top-level firebase namespace anymore. To access the Realtime Database, you'd instead use:
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";
// Set the configuration for your app
// TODO: Replace with your project's config object
const firebaseConfig = {
apiKey: "apiKey",
authDomain: "projectId.firebaseapp.com",
databaseURL: "https://databaseName.firebaseio.com",
storageBucket: "bucket.appspot.com"
};
const app = initializeApp(firebaseConfig);
// Get a reference to the database service
const database = getDatabase(app); // 👈 Get the database instance
This is shown in the documentation on initializing the Realtime Database JavaScript SDK, so I recommend keeping that handy.
If you're following a tutorial or documentation from elsewhere, it likely hasn't been updated to the new modular syntax yet. You can also use the compat mode of the new SDK in that case, as user K Lee pointed out in their answer.
After a while I realized that all your Javascript code has to be run within the SDK module tags that you import from the Firebase Dashboard...
If your Javascript is not run within the <script type="module"> tags from the imported Firebase code the imported modules from Firebase's modular SDK wont be defined.
Also I was trying to go through a tutorial that was from V5 of Firebase and was running into problems there as well.

How can i use Swrve Web SDK in Ionic

I am trying to use swrve web sdk in my ionic project but not able to initialize it. Following is the documentation link
https://docs.swrve.com/developer-documentation/integration/web/#Installing_the_SDK
I have install the SDK using npm command:
npm install #swrve/web-sdk
after that i use the import statement:
import SwrveSDK from "swrvesdk";
in a constructor function i declare it as a following
SwrveSDK.default.createInstance({
appId: <app_id>,
apiKey: "<web_api_key>",
externalUserId: "<external_user_id>",
});
but when i run ionic serve i get following error
ERROR TypeError: Cannot read property 'createInstance' of undefined
Whats the proper way for declaring npm package or web javascript libraries?
The documentation looks wrong. Plain wrong.
Try
import SwrveSDK from "#swrve/web-sdk";
SwrveSDK.createInstance({
appId: <app_id>,
apiKey: "<web_api_key>",
externalUserId: "<external_user_id>",
});
I suspected that they copied and pasted the CommonJS and then forgot to edit it.
Examination of the source code confirms this, the telltale line being
https://github.com/Swrve/swrve-web-sdk/blob/release-1_0/SwrveSDK/src/Swrve.ts#L399
The reason SwrveSDK.default.createInstance looks so suspicious is that the statement import SwrveSDK from " #swrve/web-sdk"; imports the export named default from the main module of the package, binding it to the name SwrveSDK. Of course it is conceivable that the default export could itself have a property named default but the example using CommonJS suggests otherwise.
Note that you may need to set --allowSyntheticDefaultImports and --esModuleInterop.
Also be sure that you are using TypeScript >= 2.7 or an ES module interop aware loader such as SystemJS.

undefined error at runtime while using react-redux along with ASP.NET Core

I'm using react/redux in an ASP.NET Core application and everything goes smooth if i don't include redux but after adding redux and change current components to connect to the store, i get following errors in the browser (after publish the website t wwwroot folder):
ReferenceError: Provider is not defined
or
ReferenceError: connect is not defined
...
Note that in my wwwwroot folder i have added the react-redux.js file which exists in dist folder of react-redux module in node-modules.
---node_modules\react-redux\dist\react-redux.js----
in the following i put the code of one of my containers which shows me error at runtime in the browser:
declare var { connect }: typeof import("react-redux");
import { addTodo } from '../redux/actions/todo-actions.js';
import AddTodoForm from '../components/AddTodoForm.js';
const mapDispatchToProps = {
handleSubmit: addTodo
};
export default connect<any, any, any>(null, mapDispatchToProps)(AddTodoForm)
To me it sounds like, the reaxt-redux.js that i have added to the wwwroot folder isn't exporting its interfaces (specifically connect interface) into the window properly!
Consider that i'm not having node-modules and npm on my servers so i prefer to reference the react,redux and react-redux javascript files manually in my pages.
Can you please let me know what i'm doing wrong?
Thanks in advance
I found the issue. As i was using Webpack, as i had more than one component on the page, the redux store was bundled and added more than once. Needed to change the store.tsx to prevent it.

How to do unit testing in react native that uses firebase?

Im quite new to jest unit testing, so stuff like mocking modules is confusing.
In react native, there is a component that uses firebase databse that returns data from a given ref:
// when the data of the current user is available
userRef.child(user.uid).on('value', snap => {
// check of val() consists data
if (snap.val()) {
let
authUser = snap.val(),
isPatient = authUser.type === "Patient",
// We update the state object so that the component is re-rendered
this.setState({
// the ID of the current user
authUserUID: user.uid,
// the type of the current user (i.e. Doctor or Patient)
authUserType: snap.val().type,
// title of the dashboard based on the current user type
activeTitle: snap.val().type === "Doctor" ? "My Patients" : "My Doctors",
});
}
});
I'm now trying to do unit testing which uses this component:
import 'react-native'
import React from 'react'
import renderer from 'react-test-renderer'
import LaunchScreen from "../../App/Containers/LaunchScreen";
test('LaunchScreen', () => {
const tree = renderer.create( <LaunchScreen / > ).toJSON()
expect(tree).toMatchSnapshot()
})
But it gives a weird error
RNFirebase core module was not found natively on iOS, ensure you have correctly included the RNFirebase pod in your projects Podfile and have run pod install
I have no idea since the firebase does return data if I run it. So why is it saying that RNFirebase cannot be found?
Thanks
Update
One of the answers have given a nice step by step instructions, and although it solves partially the proposed question; the error still persists. For example; I'm now getting this new error:
console.error node_modules\react-test-renderer\cjs\react-test-renderer.development.js:5530
The above error occurred in the component:
in LaunchScreen
Consider adding an error boundary to your tree to customize error handling behavior.
TypeError: _reactNativeFirebase2.default.app is not a function
https://gist.github.com/himanshusinghs/bd86262ce3c9e6f4d691b5242de707ef
Above is the link to a gist containing the mock of React Native Firebase. Implementation instructions are also there. I am summarising them here as well -
1. You will be mocking a node_module and to do so there are multiple ways depending upon your use case. But since you will need to mock Firebase for almost every component that utilizes it, we will be implementing a global mock of React Native Firebase module.
2. Create a __mocks__ folder in your project's root directory adjacent to your node_modules folder.
3. Now create a file named react-native-firebase.js inside the __mocks__ directory.
4. Copy paste the contents from RNFirebaseMock.js in the above gist to your react-native-firebase.js file.
How this works ?
Jest has an auto mocking feature. Now every time you will run your test cases using Jest, and whenever any of your test case will require react-native-firebase module, Jest will first look into __mocks__ folder and see if there is a react-native-firebase.js containing some mock implementation of the required module.
If there is then jest will require that mock implementation instead of original module otherwise it will continue on to require original react-native-firebase module.
Things to be noted
You need to observe that the name of the mock file that we created react-native-firebase.js inside __mocks__ folder is similar to the name of installation folder of actual react-native-firebase module. Just go to node_modules and scroll down till you find react-native-firebase folder.
Yes, the name of your mock implementation of a module need to be exactly same as the name of the module itself.
Things to do this point onwards
Congratulations for you started with unit testing and chose an awesome framework for the same. Trust me, testing react-native or react is such a PITA (Pain in the Ass) that you should consider going through Jest documentation seriously and primarily focus on the mock part.
Later you may very well encounter problems while setting up Jest for react-native or react and there the documentation will come in handy.
Here are some series of tutorials and references that helped me get started with Jest and unit testing react and react-native -
Jest Documentation
Testing React and React Native using Jest/Enzyme setup
Reference article for Mocks, Stubs and Fakes
Testing Redux - P1
Testing Redux - P2
Testing Redux - P3
Solution for the error after applying RNFirebaseMock
The error that you now are getting is because there doesn't exist a function named app under default export of your mock. So let create it.
Go to your mocks directory and open react-native-firebase-mock.js. look for export default class RNFirebase, inside that class there are several static methods with no implementation. Create one function doing nothing in the class with the name app.
Your default exported class should look something like this now -
export default class RNFirebase {
static initializeApp() {
RNFirebase.firebase = new MockFirebase()
RNFirebase.promises = []
return RNFirebase.firebase
}
static reset() {
RNFirebase.promises = []
RNFirebase.firebase.databaseInstance = null
}
static waitForPromises() {
return Promise.all(RNFirebase.promises)
}
static analytics () {}
static app () {}
}
This should do the trick, however I belive you are extensively using Firebase. In my case a mock implementation as simple as the one I gave you did the trick for me.
If you are extensively using most of the APIs of Firebase then you are bound to get more errors like you just saw because we haven't yet added mock implementations for all the APIs of RNFirebase in our Firebase mock.
If that case shall ever arise, I would suggest that you look at this mock implementation of Firebase which I guess covers the Firebase completely.
Jest runs in node and does not have access to the native apis, so you'll need to mock the react-native-firebase / RNFirebase module for this to work.
see https://github.com/invertase/react-native-firebase/issues/162

Categories

Resources