I used Firebase Realtime Database with Next.js, for back-end.
And I wrote the below code. But It works only in local, not in production. The reason I comments some lines as follows is that I want to show that the error was not caused by my code. onValue, get, set, update were all the same. The same error was raised. And also I confirmed that effect function in useEffect() runs only once.
/* lib/firebase.ts */
import { initializeApp } from 'firebase/app';
import { getDatabase } from 'firebase/database';
// Initialize Firebase
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
// Initialize Realtime Database
export const database = getDatabase(app);
import { onValue, ref, update } from 'firebase/database';
import { database } from 'lib/firebase';
...
useEffect(() => {
onValue(
ref(database, `objects/${user.uid}`),
(snapshots) => {
console.log(snapshots);
// const fetchedObjects: Common.Object[] = [];
// snapshots.forEach((snapshot) => {
// fetchedObjects.push({ key: snapshot.key, ...snapshot.val() } as Common.Object);
// });
// setTimeout(() => {
// setObjects(fetchedObjects);
// setIsObjectLoaded(true);
// }, 500);
}
);
}, []);
As a result of console.log(), a snapshot object with no children was returned. But It should be a snapshot object with serveral child nodes according to database state. It is the case in local.
Only in production, the below error was raised. _app-e9aaf40698fc4780.js was bundled by Next.js, so It was so complicated that I couldn't read it. But when I deduce from comments, maybe it can be firebase/database code.
Uncaught RangeError: Maximum call stack size exceeded
at i (_app-e9aaf40698fc4780.js:1486:770)
at i (_app-e9aaf40698fc4780.js:1486:897)
at i (_app-e9aaf40698fc4780.js:1486:906)
at i (_app-e9aaf40698fc4780.js:1486:897)
at i (_app-e9aaf40698fc4780.js:1486:906)
at i (_app-e9aaf40698fc4780.js:1486:897)
at i (_app-e9aaf40698fc4780.js:1486:906)
at i (_app-e9aaf40698fc4780.js:1486:897)
at i (_app-e9aaf40698fc4780.js:1486:906)
at i (_app-e9aaf40698fc4780.js:1486:897)
1486 line's code is here.
*/ let e3,e4,e6=new class extends eW{compare(e,t){let n=e.node.getPriority(),r=t.node.getPriority(),i=n.compareTo(r);return 0===i?q(e.name,t.name):i}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return eq.MIN}maxPost(){return new eq(j,new e2("[PRIORITY-POST]",e4))}makePost(e,t){let n=e3(e);return new eq(t,new e2("[PRIORITY-POST]",n))}toString(){return".priority"}},e5=Math.log(2);class e8{constructor(e){var t;this.count=parseInt(Math.log(e+1)/e5,10),this.current_=this.count-1;let n=parseInt(Array(this.count+1).join("1"),2);this.bits_=e+1&n}nextBitIsOne(){let e=!(this.bits_&1<<this.current_);return this.current_--,e}}let e9=function(e,t,n,r){e.sort(t);let i=function(t,r){let s=r-t,o,a;if(0===s)return null;if(1===s)return o=e[t],a=n?n(o):o,new eG(a,o.node,eG.BLACK,null,null);{let l=parseInt(s/2,10)+t,u=i(t,l),c=i(l+1,r);return o=e[l],a=n?n(o):o,new eG(a,o.node,eG.BLACK,u,c)}},s=new e8(e.length),o=function(t){let r=null,s=null,o=e.length,a=function(t,r){let s=o-t;o-=t;let a=i(s+1,o),u=e[s],c=n?n(u):u;l(new eG(c,u.node,r,null,a))},l=function(e){r?(r.left=e,r=e):(s=e,r=e)};for(let u=0;u<t.count;++u){let c=t.nextBitIsOne(),h=Math.pow(2,t.count-(u+1));c?a(h,eG.BLACK):(a(h,eG.BLACK),a(h,eG.RED))}return s}(s);return new eY(r||t,o)},e7,te={};class tt{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return(0,f.hu)(te&&e6,"ChildrenNode.ts has not been loaded"),e7=e7||new tt({".priority":te},{".priority":e6})}get(e){let t=(0,f.DV)(this.indexes_,e);if(!t)throw Error("No index defined for "+e);return t instanceof eY?t:null}hasIndex(e){return(0,f.r3)(this.indexSet_,e.toString())}addIndex(e,t){(0,f.hu)(e!==e$,"KeyIndex always exists and isn't meant to be added to the IndexMap.");let n=[],r=!1,i=t.getIterator(eq.Wrap),s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();let o;o=r?e9(n,e.getCompare()):te;let a=e.toString(),l=Object.assign({},this.indexSet_);l[a]=e;let u=Object.assign({},this.indexes_);return u[a]=o,new tt(u,l)}addToIndexes(e,t){let n=(0,f.UI)(this.indexes_,(n,r)=>{let i=(0,f.DV)(this.indexSet_,r);if((0,f.hu)(i,"Missing index implementation for "+r),n===te){if(!i.isDefinedOn(e.node))return te;{let s=[],o=t.getIterator(eq.Wrap),a=o.getNext();for(;a;)a.name!==e.name&&s.push(a),a=o.getNext();return s.push(e),e9(s,i.getCompare())}}{let l=t.get(e.name),u=n;return l&&(u=u.remove(new eq(e.name,l))),u.insert(e,e.node)}});return new tt(n,this.indexSet_)}removeFromIndexes(e,t){let n=(0,f.UI)(this.indexes_,n=>{if(n===te)return n;{let r=t.get(e.name);return r?n.remove(new eq(e.name,r)):n}});return new tt(n,this.indexSet_)}}/**
I can't interpret the code, and I can't figure out the cause, so I'm going crazy. Help me.
+) I also tested on the new Next.js project created by create-next-app.
npx create-next-app#latest --typescript
cd {project folder name}
npm install firebase
And the code I wrote is here.
import "../styles/globals.css";
import type { AppProps } from "next/app";
import { useEffect } from "react";
import { initializeApp } from "firebase/app";
import { getDatabase, onValue, ref } from "firebase/database";
function MyApp({ Component, pageProps }: AppProps) {
useEffect(() => {
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
// It works only in local
onValue(ref(db, "???"), (snapshots) => console.log(snapshots));
}, []);
return <Component {...pageProps} />;
}
export default MyApp;
As a result, like my project, the same error was raised. But It works well in local.
I'm the author of this post.
I resolved this problem by downgrading Next.js version from 12.3.1 to 12.3.0.
I am trying to run my tests with cypressv10 and with latest #badeball/cypress-cucumber-preprocessor, but failing at the index.js ..can some one pls help
my index.js:
const cucumber = require("#badeball/cypress-cucumber-preprocessor").default;
module.exports = (on, config) => {
on("file:preprocessor", cucumber());
};
In cypress 10 the way to specify the plugins by using the file plugin/index.js was deprecated.
I had your same issue and was able to resolve it by using the library #bahmutov/cypress-esbuild-preprocessor
This is how the cypress.config.ts file looks like now.
import { defineConfig } from "cypress";
import createBundler from "#bahmutov/cypress-esbuild-preprocessor";
import { addCucumberPreprocessorPlugin } from "#badeball/cypress-cucumber-preprocessor";
import createEsbuildPlugin from "#badeball/cypress-cucumber-preprocessor/esbuild";
async function setupNodeEvents(
on: Cypress.PluginEvents,
config: Cypress.PluginConfigOptions
): Promise<Cypress.PluginConfigOptions> {
await addCucumberPreprocessorPlugin(on, config);
on(
"file:preprocessor",
createBundler({
plugins: [createEsbuildPlugin(config)],
})
);
// Make sure to return the config object as it might have been modified by the plugin.
return config;
}
export default defineConfig({
e2e: {
...
setupNodeEvents
}
});
Please note that this example is for typescript, In here you can see the official examples including the setup for raw js.
I am trying to import a .node binary addon in an ESM & Node Typescript based context. However, when I try to do this I get the following error "error TS2307: Cannot find module './addon.node' or its corresponding type declarations."
I've looked online for several solutions, these are my versions:
NodeJS: v16.14.1
ts-node: v10.7.0
Typescript: 4.6.3
This is my current approach for importing:
import addon from "./addon.node";
Just to note, because of my configuration I am limited to only using import.
Thanks in advance for any support.
Node.js import doesn’t support .node files. To import such files in an ESM context, you need to use createRequire:
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const addon = require('./addon.node');
You could also import the .node file in a CommonJS file that an ESM file then imports.
// addon.cjs
module.exports = require('./addon.node');
// main.js
import addon from './addon.cjs';
Finally, you could create an ESM loader that adds support for .node files to import, by wrapping the createRequire method into a loader (untested):
import { cwd } from 'node:process';
import { pathToFileURL } from 'node:url';
const baseURL = pathToFileURL(`${cwd()}/`).href;
export async function resolve(specifier, context, nextResolve) {
if (specifier.endsWith('.node')) {
const { parentURL = baseURL } = context;
// Node.js normally errors on unknown file extensions, so return a URL for
// specifiers ending in `.node`.
return {
shortCircuit: true,
url: new URL(specifier, parentURL).href,
};
}
// Let Node.js handle all other specifiers.
return nextResolve(specifier);
}
export async function load(url, context, nextLoad) {
if (url.endsWith('.node')) {
const source = `
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const path = fileURLToPath(${url});
export default require(path);`;
return {
format: 'module',
shortCircuit: true,
source,
};
}
// Let Node.js handle all other URLs.
return nextLoad(url);
}
guys
I am learning redux, and try to run a very simple example code in node.js environment. I got the following error when I try to use :
import { createSlice, configureStore } from '#reduxjs/toolkit' .
The errors is:
import { createSlice, configureStore } from '#reduxjs/toolkit'
^^^^^^^^^^^
SyntaxError: Named export 'createSlice' not found. The requested module '#reduxjs/toolkit' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from '#reduxjs/toolkit';
const { createSlice, configureStore } = pkg;
at ModuleJob._instantiate (internal/modules/esm/module_job.js:120:21)
at async ModuleJob.run (internal/modules/esm/module_job.js:165:5)
at async Loader.import (internal/modules/esm/loader.js:177:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
If I use import like what the error tip says:
import pkg from '#reduxjs/toolkit';
const { createSlice, configureStore } = pkg;
All is OK.
What I want to ask is:
It gives me a wrong example in the official website of Redux? Or Just I run the example with a wrong way?
The following is the detail information.
My Node.js version is: v14.17.3
1 Init a node project:
mkdir redux_01
cd redux_01
yarn init
yarn add #reduxjs/toolkit
2 Modify the 'package.json', add a line in it:
"type":"module"
3 Create a file 'index.js' with the "Redux Toolkit Example" code parsed from https://redux.js.org/introduction/getting-started.
import { createSlice, configureStore } from '#reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0
},
reducers: {
incremented: state => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1
},
decremented: state => {
state.value -= 1
}
}
})
export const { incremented, decremented } = counterSlice.actions
const store = configureStore({
reducer: counterSlice.reducer
})
// Can still subscribe to the store
store.subscribe(() => console.log(store.getState()))
// Still pass action objects to `dispatch`, but they're created for us
store.dispatch(incremented())
// {value: 1}
store.dispatch(incremented())
// {value: 2}
store.dispatch(decremented())
// {value: 1}
4 Now I run it like this:
node index.js
I then got that error message that I just mentioned.
The reason for the error is explained here:
https://lightrun.com/answers/reduxjs-redux-toolkit-cannot-import-redux-toolkit-from-a-nodejs-esm-module "here"
solution:
import * as toolkitRaw from '#reduxjs/toolkit';
const { createSlice,configureStore } = toolkitRaw.default ?? toolkitRaw;
or in Typescript:
import * as toolkitRaw from '#reduxjs/toolkit';
I found npm module google-maps-api and installed it (npm install google-maps-api) but I can't figure out how to import it with systemjs/jspm (jspm cannot find this module). Here's the configuration from my config.js:
"paths": {
"*": "app/dist/*.js",
"github:*": "app/jspm_packages/github/*.js",
"npm:*": "app/jspm_packages/npm/*.js" }
So, when I try do something like this:
import {mapsapi} from 'google-maps-api';
I get the following error in browser console:
GET https://localhost:44308/app/dist/google-maps-api.js 404 (Not Found)
Looking at the filesystem I see that npm installed the module under app/node_modules/google-maps-api so how do I reference it in the import clause from Aurelia module?
I found a solution and answering my own question here:
I finally figured how to install it with jspm, so you just need to give a hint to jspm to install it from npm like so:
jspm install npm:google-maps-api
After jspm completes installation, import (no {} syntax) works fine:
import mapsapi from 'google-maps-api';
then I inject it in constructor and instantiate geocoder api:
#inject(mapsapi('InsertYourGMAPIKeyHere'))
export class MyClass {
constructor(mapsapi) {
let that = this;
let maps = mapsapi.then( function(maps) {
that.maps = maps;
that.geocoder = new google.maps.Geocoder();
});
...
}
In order to create map on a div I use EventAggregator to subscribe for router:navigation:complete event and use setTimeout to schedule map creation:
this.eventAggregator.subscribe('router:navigation:complete', function (e) {
if (e.instruction.fragment === "/yourRouteHere") {
setTimeout(function() {
that.map = new google.maps.Map(document.getElementById('map-div'),
{
center: new google.maps.LatLng(38.8977, -77.0366),
zoom: 15
});
}, 200);
}
});
Here's a complete view-model example that uses attached() to link to your view.
import {inject} from 'aurelia-framework';
import mapsapi from 'google-maps-api';
#inject(mapsapi('your map key here'))
export class MapClass {
constructor(mapsAPI) {
this.mapLoadingPromise = mapsAPI.then(maps => {
this.maps = maps;
});
}
attached() {
this.mapLoadingPromise.then(() => {
var startCoords = {
lat: 0,
long: 0
};
new this.maps.Map(document.getElementById('map-div'), {
center: new this.maps.LatLng(startCoords.lat, startCoords.long),
zoom: 15
});
});
}
}
For everyone using Typescript and getting "Cannot find module 'google-maps-api'" error,
you need to add typings to the solution. Something like this works
declare module 'google-maps-api' {
function mapsapi(apikey: string, libraries?, onComplete?);
namespace mapsapi {
}
export = mapsapi;
}
and then import it like this
import * as mapsapi from 'google-maps-api';