How to configure firebase-admin sdk - javascript

~Hello, I'm developing a user control system with google firebase.
Only 2 functions for the moment: add users and remove them.
For add a user is so easy, I only need to copy and paste the autogenerated script from the console, but the problem here is delete a user because I need admin-level auth for this, so, I've reading about node.js and I have a VPS running on Centos7, so I proceeded whith the instalation:
yum install npm
Then in the folder of my domain I used the following:
npm init
For generate the initial package.json:
npm install firebase-admin --save
And then I had no idea how to use it, since I understand that the function require is not defined for browsers since it is backend, I mean for the following error in the browser:
Uncaught ReferenceError: require is not defined
Reading a bit more I found that I can use something called webpack (the first time I use it) and I followed the next instructions:
npm install --save-dev ts-loader webpack-node-externals
npm install --global webpack
Then, my configuration files:
webpack.config.js
'use strict';
var nodeExternals = require('webpack-node-externals');
module.exports = {
entry: './index.ts',
output: {
filename: 'index.js',
libraryTarget: 'this'
},
target: 'node',
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
transpileOnly: true
}
}
]
},
resolve: {
extensions: [ '.ts', '.tsx', '.js' ]
},
externals: [nodeExternals()]
};
tsconfig.json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./",
"noImplicitAny": true,
"strictNullChecks": false
},
"include": [
"./*.ts"
],
"exclude": [
"node_modules"
]
}
index.ts
const admin = require('firebase-admin');
const serviceWorker = require('./<MY_PRIVATE_KEY>.json');
admin.initializeApp({
credential: admin.credential.cert(serviceWorker),
databaseURL: "https://<MY_DATABASE>.firebaseio.com/"
});
and after running the webpack command, is generated the index.js file that should be included in my website... but the problem is... I still have a error... (complete error in the attached image)
Error of my website in the generated index.js
So...
I would appreciate if you help me solve the error... I'm a new in node.js
I only want to run the delete user function:
admin.auth().deleteUser(uid)
.then(function() {
alert("Successfully deleted user");
})
.catch(function(error) {
alert("Error deleting user:" + error);
});

Related

How to import javascript files in background.js in chrome extension using version 3

I am building a chrome extension in version 3 using firebase firestore. I have downloaded all the api in extension and I want to use importScript to fetch the api example: firebase-app.js and firebase-firestore.js. but it not working for me. The error in the console says "TypeError: Failed to execute 'importScripts' on 'WorkerGlobalScope': Module scripts don't support importScripts().".
Is 3 days now searching the net but no solution. Please any help?
Code of the issue
Here's a quick solution: in short, you will need to install webpack, which is a module bundler (it means that its main purpose is to bundle JavaScript files for usage in a browser). If you have npm already set up, you can execute this command in your project:
npm install webpack
After you have done that you can proceed to set up firebase (which, from what I can see from your image, you have already done). You will need to run another command:
npm install firebase
Continuing the setup of webpack, you will need to create a webpack.config.js file and there set the entry and the output. Again, you can find plenty of tutorials online, but here's a quick example implementation:
webpack.config.js:
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');
const path = require('path');
module.exports = {
mode: 'production',
entry: {
main: './src/main'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
],
},
],
},
devServer: {
contentBase: './dist',
overlay: true,
hot: true
},
plugins: [
new CopyWebpackPlugin({
patterns: [
{ from: 'manifest.json', to: 'manifest.json' },
],
}),
new CopyWebpackPlugin({
patterns: [
{ from: 'images', to: 'images' },
],
}),
new CopyWebpackPlugin({
patterns: [
{ from: 'popup.html', to: 'popup.html' },
],
}),
new webpack.HotModuleReplacementPlugin()
],
};
Once you've done that, in your entry file (the entry point), you can import firebase and set it up:
main.js
import { initializeApp } from 'firebase/app';
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
//...
};
const app = initializeApp(firebaseConfig);
When you run npm start, webpack will create another folder (the 'dist' folder). This folder is the chrome exstension with firebase set up!
Hope I was able to help you. If you have any questions feel free to ask!

typescript and sweetalert2 Uncaught ReferenceError: exports is not defined

Started a brand new .net core 2.0 project to start learning and i have opted to make use of and learn typescript.
i have been following the guide located here: typescript guide
This compiles and works fine.
I then wanted to make use of sweetalert2 which i have used in the past and i followed these instructions sweetalert2
i created a simple helloWorld() in the ts file
import swal from 'sweetalert2'
function swalHelloWorld() {
swal('hello world!');
}
which compiles in a js file of my www folder too
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var sweetalert2_1 = require("sweetalert2");
function swalHelloWorld() {
sweetalert2_1.default('hello world!');
}
and included on the _layout page
Now when i run my project i get the following err
Uncaught ReferenceError: exports is not defined
at app.js:2 (anonymous) # app.js:2
line 2 is the following
Object.defineProperty(exports, "__esModule", { value: true });
i tried following the guide here to correct it but this didnt help
my tsconfig.json is
{
"compilerOptions": {
"noImplicitAny": true,
"noEmitOnError": true,
"sourceMap": true,
"target": "es5",
"module": "commonjs",
"moduleResolution": "node"
},
"files": [
"./scripts/app.ts"
],
"exclude": [
"node_modules",
"wwwroot"
],
"compileOnSave": true
}
i am unsure how to resolve this issue
webpack config
var path = require('path');
module.exports = {
entry: {
site: [
'./Scripts/app.ts']
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'wwwroot/dist/')
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
},
]
},
resolve: {
extensions: [".tsx", ".ts", ".js"]
}
};
git repo: https://github.com/iamthebarnsley/TSExample
It looks like your HTML page is still referencing app.js. If you wanted to follow the guide you linked, the HTML page should instead reference the bundle.js file produced by Webpack.
Round 2
If you want to call swalHelloWorld from your HTML with <input id="swalalert" type="button" value="swal alert" onclick="swalHelloWorld();" />, then you need to define swalHelloWorld globally:
import swal from 'sweetalert2'
function swalHelloWorld() {
swal('hello from sweet alert');
}
(<any>window).swalHelloWorld = swalHelloWorld;
Without this, Webpack is being clever and realizing there is no way to call swalHelloWorld (since it is not exported from the module either) and omitting it from the output. When I make this change and also replace build/app.js with dist/bundle.js in the HTML as previously discussed, the alert is working for me.
Update, 2018-09-30
I learned about a cleaner solution: add the library option to the Webpack configuration as shown here with a name of your choice (for example, swalHelloWorld), and that will define a global variable named swalHelloWorld representing the entire entry-point module. Then if you export a function from the module:
import swal from 'sweetalert2'
export function swalHelloWorld() {
swal('hello from sweet alert');
}
the HTML will be able to call it as swalHelloWorld.swalHelloWorld(...) or similar.

"webpack" vs "webpack --watch" creates different output

Im using this set up as the base of my project: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html
When I run webpack, it compiles a bundle that works in the browser.
When I run webpack --watch, it re-compiles on file change, but causes this error in the browser:
Uncaught ReferenceError: exports is not defined
I looked at the output of both, and it looks like webpack --watch does not include the webpack bootstrap code or my modules - only the entry file transpiled.
webpack
Includes all of my modules in a single file, along with using webpacks own module require.
E.g: var io = __webpack_require__(20);
webpack --watch
Only includes my entry module - no other modules, no __webpack_require__.
E.g. var io = require("socket.io-client");
Versions:
- webpack: 3.7.1
- tsc: 1.8.10
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "bundle.js",
path: __dirname + "/dist"
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
{ test: /\.tsx?$/, loader: "awesome-typescript-loader" },
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
]
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
"react": "React",
"react-dom": "ReactDOM"
}
The fix is to remove outDir from tsconfig.json:
{
"compilerOptions": {
"outDir": "./dist/"
}
}
It was the tsconfig.json file having a conflicting output directory. Files are only written by typescript when using webpack --watch

What's the difference between tsconfig's 'outFile' and webpack config's 'output'

What's different between the 'output' path? Is tsconfig is a loader? And webpack to resolve '.ts' file after the run tsconfig build?
Why the file 'src.js' is not found? It is deleted by webpack automatically?
tsconfig.json:
{
"compilerOptions": {
"module": "amd",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"outFile": "src.js",
"sourceMap": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}
webpack.config.js:
module.exports = {
entry: './index.ts',
output: {
filename: './dest.js'
},
module: {
loaders: [{
test: /\.ts$/,
loader:'ts-loader'
}]
},
resolve: {
extensions: ['.webpack.js', '.web.js', '.ts', '.js']
}
}
When I run 'webpack' the 'src.js' is not found and 'dest.js' is ok.
Thanks a lot.
outFile
This configuration option is used by TS compiler when using tsc command to
Concatenate and emit output to single file.
You can read more about compiler options here.
output
This configuration option is used by Webpack to
The top-level output key contains set of options instructing webpack
on how and where it should output your bundles, assets and anything
else you bundle or load with webpack.
Why src.js is missing
When you use ts-loader instead of a tsc as part of webpack built, the outFile option from tsconfig.json is not used. Webpack when loading a .ts file detects that it should be passed to ts-loader, which in turn uses a compiler to compile only this one file and then returns output to a webpack. It never works with all files the way tsc does. That's why no src.js is generated.

Unable to switch from JS to TS in ionic 2

I changed the file extensions of my app files including app/app.js
Error: Cannot find module 'app/app.js' from 'app_folder'
It doesn't tell me which file I should be looking at to fix the error.
I tried looking with git grep and read a bit about Angular2's entry points to find out where it is loaded, but no luck yet.
Using TypeScript into an Ionic2 project isn't just switching extensions of files ;-)
You need to integrate the TypeScript compiler into Gulp with the gulp-tsc' plugin:
var typescript = require('gulp-tsc');
(...)
gulp.task('compile', function() {
gulp.src(paths.src)
.pipe(typescript({
emitError: false
}))
.pipe(gulp.dest('www/js/'))
});
This page could help you:
https://github.com/driftyco/ionic-typescript-example
Thierry Templier put me on the right track, and here is the answer.
Documentation in case anyone else is wondering.
Ionic2 is different than ionic1 basically uses browserify now. To switch from ES6 to TS, you would need to setup typscirpt for your project and set the dependencies like so:
in gulpfile.js change var buildBrowserify = require('ionic-gulp-browserify-es2015');
for var buildBrowserify = require('ionic-gulp-browserify-typescript');
in package.json change ionic-gulp-browserify-es2015": "^1.0.2"
for "ionic-gulp-browserify-typescript": "^1.0.0"
Install typescript
3.1 npm install typings --global
3.2 tsd query node --action install --save
Make sure you have the file your_app/typings/main.d.ts
with the content: /// <reference path="main/ambient/es6-shim/index.d.ts" />
lastly the tsconfig.json file
tsconfig{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"emitDecoratorMetadata": true,
"experimentalDecorators": true
},
"filesGlob": [
"**/*.ts",
"!node_modules/**/*"
],
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts"
],
"compileOnSave": false,
"atom": {
"rewriteTsconfig": false
}
}

Categories