firebase.database() is not a function - new Firebase Project - javascript

Apologies for what will likely be a beginners mistake. I have searched for days to try and find the answer, but am unable to successfully connect to a Firebase Database.
Extracts of all files are below.
I have installed node.js, then firebase init, firebase login, and then firebase serve.
I get the same result whether hosting locally, or after deploying to firebase hosting. I have tried the full paths to the firebase js files previously and similarly got the same result.
What do I need to do to be able to prove its connecting to Firebase ok?
Many many thanks!
index.html...
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script src="/__/firebase/4.0.0/firebase-app.js"></script>
<script src="/__/firebase/4.0.0/firebase-auth.js"></script>
<script src="/__/firebase/4.0.0/firebase-database.js"></script>
<script src="/__/firebase/init.js"></script>
<script src="app.js"></script>
<title>Page Title</title>
I'm the header ...
</head>
<body>
I'm the body...
<script> getDatabaseRef() </script>
</body>
</html>
app.js...
function getDatabaseRef(){
console.log('Script called');
var firebaseRef = firebase.Database().ref();
console.log(firebaseRef.ref);
window.alert(firebaseRef);
console.log('Script finished');
}
firebase.json....
{
"database": {
"rules": "database.rules.json"
},
"hosting": {
"public": ".",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
package.json
{
"name": "jobsheetpoc",
"version": "1.0.0",
"description": "my JS proof of concept",
"main": "app.js",
"dependencies": {
"firebase": "^4.0.0"
},
"devDependencies": {
"firebase-server": "^0.10.1"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Jim",
"license": "ISC",
"keywords": [
"job",
"sheet",
"poc"
]
}
Output in Browser...
Output in Browser Window

I have a strange feeling you made a typo. You have a capital Database in firebase.Database instead of a normal one (firebase.database).

Related

error when attempting to display WebView in vs code

I am learning how to display a webview on vs code. i used this website and the code below is copied from it. https://mishka.codes/webviews-in-vscode#:~:text=Webviews%20display%20custom%20HTML%2C%20CSS%20%26%20JS%20inside,CSS%20and%20Javascript%20files%20to%20the%20webview.%20
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
let openWebview = vscode.commands.registerCommand('exampleApp.openWebview', () => {
const panel = vscode.window.createWebviewPanel(
'openWebview', // Identifies the type of the webview. Used internally
'Example Page', // Title of the panel displayed to the user
vscode.ViewColumn.One, // Editor column to show the new webview panel in.
{ // Enable scripts in the webview
enableScripts: true //Set this to true if you want to enable Javascript.
}
);
}
context.subscriptions.push(openWebview);
}
function getWebviewContent() {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example Webview</title>
</head>
<body>
<h1>This works!</h1>
//Add some custom HTML here
</body>
</html>`;
}
There is an error in the authors extension.ts but it goes away when edit the code so it looks like this (all i added as a ')' and a ';' above the word context):
...
{ // Enable scripts in the webview
enableScripts: true //Set this to true if you want to enable Javascript.
}
);
});
context.subscriptions.push(openWebview);
}
However, when i run the extension the HTML does not show up on the tab in VS code. Can someone help me identify what is wrong? I have left the package-lock.json as is (i used yo code to skaffold the extension). i will post my package.json below
{
"name": "webview",
"displayName": "webview",
"description": "webview test",
"version": "0.0.1",
"engines": {
"vscode": "^1.54.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:exampleApp.openWebview"
],
"main": "./out/extension.js",
"contributes": {
"commands": [
{
"command": "exampleApp.openWebview",
"title": "Open webview"
}
]
},
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"pretest": "npm run compile && npm run lint",
"lint": "eslint src --ext ts",
"test": "node ./out/test/runTest.js"
},
"devDependencies": {
"#types/vscode": "^1.54.0",
"#types/glob": "^7.2.0",
"#types/mocha": "^9.1.1",
"#types/node": "16.x",
"#typescript-eslint/eslint-plugin": "^5.31.0",
"#typescript-eslint/parser": "^5.31.0",
"eslint": "^8.20.0",
"glob": "^8.0.3",
"mocha": "^10.0.0",
"typescript": "^4.7.4",
"#vscode/test-electron": "^2.1.5"
}
}

"Failed to load resource" and other errors running and modifying firebase firestore app tutorial

I'm following the Firebase Firestore tutorial located at https://firebase.google.com/docs/firestore/quickstart to learn how to use the Firestore No- SQL document store.
I built the simple app using the npx webpack –watch command so I could refresh the page and get updated changes on the fly. Webpack puts the main.js or bundle.js file in the dist folder of the project root.
I have made several changes to the 'index.html' script tag in vain to get the app working.
If I use <script src=”dist/main.js”></script> or <script src=”main.js”></script> I get the following:
If I use:
<script src=”index.js”></script> I get the following error:
So I used the <script type=module attribute.
If I use: <script type=module src="index.js"></script> I get the following:
So I thought I would put a "/" and a "./" in front of index.js
If I use: <script type=module src="/index.js"></script> or <script type=module src="./index.js"></script>
I get the same error as above:
What's going on here?
Here is the file structure:
Project Root
>dist
-main.js
>node_modules
>src
-index.html
-index.js
>package.json
>package-lock.json
>webpack.config.js
Here are the key files:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Simple Cafe</title>
</head>
<body>
<p>
<h2>Hello Firestore!</h2>
</p>
<script type=module src="index.js"></script>
</body>
</html>
index.js
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore, doc, setDoc } from "firebase/firestore";
import { getAnalytics } from "firebase/analytics"
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: <apiKey>
authDomain: <authDomain>
databaseURL: <databaseURL>
projectId: <projectId>
storageBucket: <storageBucket>
messagingSenderId: <messagingSenderId>
appId: <appId>
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const firestore = getFirestore();
const specialOfTheDay = doc(firestore, 'dailySpecial/2021-09-14')
function writeDailySpecial(){
const docData = {
description: 'A delicious vanilla latte',
price: 3.99,
milk: 'Whole',
vegan: false,
};
setDoc(specialOfTheDay, docData)
}
console.log("Hello , Firestore!")
writeDailySpecial();
webpack.config.js
const path = require('path');
module.exports = {
mode: 'development',
entry: '/src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.js',
}
}
package.json
{
"dependencies": {
"firebase": "^9.0.2"
},
"devDependencies": {
"serve": "^13.0.2",
"webpack": "5.52.1",
"webpack-cli": "^4.8.0",
"webpack-dev-server": "^4.7.2"
},
"name": "simplecafe",
"version": "1.0.0",
"description": "Tutorial from https://firebase.google.com/docs/firestore/quickstart",
"main": "index.js",
"scripts": {
"test": "echo\"Error: no test specified\" && exit 1",
"build": "webpack"
},
"author": "Todd Kerpelman",
"license": "ISC"
}
Thanks in advance.

ERR_FILE_NOT_FOUND bundle.js

I'm starting to use webpack, and I did a tiny project to try, but I'm finding an error that I don't know how to fix. When I run my index.html, it says that can't find bundle.js. I think is something wrong with the path, but I'm not sure. Hope someone can help me!
This is my structure
prueba1
node_modules
build
bundle.js
src
app.js
index.html
messages.js
style.css
package.lock.json
package.json
webpack.config.js
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Document</title>
<link href="style.css" />
</head>
<body>
<button id="connect">Conectar</button>
<script src="bundle.js"></script>
</body>
</html>
package.json
{
"name": "prueba1",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"webpack": "^5.51.1"
},
"devDependencies": {
"webpack-cli": "^4.8.0"
}
}
webpack.config.js
const path = require("path");
module.exports = {
entry: "./src/app.js",
output: {
filename: "bundle.js",
path: __dirname + "/build",
},
};
The problem is that your index.html and your bundle.js are in different directories (src and build). You could simply move your index.html to build and it will work.
Or you let webpack do that work with the copy-webpack-plugin (https://www.npmjs.com/package/copy-webpack-plugin): install it using npm install copy-webpack-plugin --save-dev, and add this to your webpack.config.js:
const CopyPlugin = require("copy-webpack-plugin");
module.exports = {
plugins: [
new CopyPlugin({
patterns: [
{ from: "src", to: "build" }
],
}),
],
};

Why will my electron.js app not open when I try npm start even though my code is right?

I need help with my simple hello world program based for electron.js.
I was reading the quick guide documentation on the official electronjs.org website.
Esentially I did everything it told me to do on that page including the package.json, package-lock.json, index.html and main.js; and installing electron.js however when I tried to boot up my program in cmd using npm start, I just got 2 messages instead of the program opening.
From there it shows me the cmd command line again waiting for an input which is shown in the picture
I don't know what's wrong and no matter how much I try to edit the package.json and the main.js it still seems to spit out the same error. I was getting so desperate that I just copy and pasted the exact same code in the docs and just edited the author and description as asked in the quick guide.
I am well and truly stuck if anyone has any ideas on how to fix this please let me know, I've also tried some simple troubleshooting, the simple reinstall of the electronjs API, tried administrator cmd, read the forums etc and I can't find anything code will be below..
main.js
const { app, BrowserWindow } = require('electron')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('index.html')
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body style="background: white;">
<h1>Hello World!</h1>
<p>
We are using node <script>document.write(process.versions.node)</script>,
Chrome <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron)</script>.
</p>
</body>
</html>
package.json
{
"name": "my-first-electron",
"version": "1.0.0",
"description": "",
"main": "main.js",
"dependencies": {
"aws-sdk": "^2.814.0",
"electron": "^11.1.0",
"electron.js": "^0.0.1"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "electron ."
},
"keywords": [],
"author": "",
"license": "ISC"
}

How to create basic Node.js project with materialwebcomponents?

I am relatively new to Node.js. This is a very simple program so far, meant to just test the incorporation of material-components-web. I followed the instructions step-by-step in the readme, and this is what I have so far:
package.json
{
"name": "hello-polymer", "version": "0.1.0",
"description": "Intro to Polymer", "main": "index.js",
"scripts": { "start": "node index.js" },
"author": "vcapra1", "license": "ISC",
"dependencies": { "#webcomponents/webcomponentsjs": "^2.0.2" }
}
index.js
http = require('http')
fs = require('fs')
http.createServer((request, response) => {
response.statusCode = 200
response.setHeader('Content-Type', 'text/html')
let filename = "./" + request.url
if (request.url.startsWith("/#")) {
filename = "./node_modules/" + request.url
} else if (request.url == "/") {
filename = "./index.html"
} else {
response.statusCode = 404;
response.end("404 Not Found");
}
fs.readFile(filename, (err, data) => {
console.log("Request: ", request.url);
response.end(data)
})
}).listen(3000)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MWC Test</title>
<script src="#webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
<script type="module" src="#material/mwc-icon/mwc-icon.js"></script>
</head>
<body>
Hello, World
<mwc-icon>sentiment_very_satisfied</mwc-icon>
</body>
</html>
Then I run the following command in the project folder:
polymer serve
I've also tried starting it with npm using:
npm start
Both commands allow me to go to the webpage at http://localhost:XXXX, but each time all I get is the text "Hello, World sentiment_very_satisfied", and the plain text stays there with no icon.
I'm not really sure what I'm missing. I find it strange that the script src attributes reference #webcomponents as a sibling folder while said folder is actually in the node_modules directory, so I tried changing that, but still no luck.
I got it working by running with
polymer serve --module-resolution=node --npm.
This tells polymer-cli to transform npm style references to relative references when serving files. Although it doesn't work for index.html for some reason, so relative paths are required there:
<script src="node_modules/#webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
<script type="module" src="node_modules/#material/mwc-icon/mwc-icon.js"></script>
You can read more here https://www.polymer-project.org/blog/2018-03-23-polymer-3-latest-preview#packagenames

Categories