How do I fix "unexpected token 'export'" error when I try to use uuid package? - node.js

I'm working in a vue.js application with node.js in the backend. We've installed the npm package uuid in the backend but it's not working.
Our package.json file in the backend contains this:
"uuid": "^8.2.0",
In our controller, in the constructor, we have this:
this.uuid = require("uuid");
And we use it like this:
const id = this.uuid.v1();
The problem is, when we call the endpoint on the backend, we get this error:
C:\...\backend\node_modules\uuid\dist\esm-browser\index.js:1
export { default as v1 } from './v1.js';
^^^^^^
SyntaxError: Unexpected token 'export'
Googling this issue, the only solutions I've found involve importing v1 specifically, such as this:
import {v1 as uuid} from "uuid";
But since we're using node.js on the backend, we get this error:
SyntaxError: Cannot use import statement outside a module
How can I solve this problem?

I have been there. Used this approach:
const uuid = require('uuid');
const newUuid = uuid.v4();
You may use .v1() instead of .v4().

You should first export your functions (that you need in other modules) in v1.js like below-
function xyz() {
}
module.exports = xyz;
You can then use this in the respective files as-
const xyz = require(‘../pathname’);

Related

Firebase getAuth() throws error getProvider of undefined but can access database

I have the following code running on a Node server.
import admin from 'firebase-admin';
import {getAuth} from 'firebase/auth';
class MyFirebase {
constructor() {
console.log("MyFirebase Constructor");
this.firebaseApp = admin.initializeApp({
credential: admin.credential.cert("PATH_TO_CERT/cert.json"),
databaseURL: "https://DATABASE_URL",
});
console.log("App name="+firebaseApp.name);
this.defaultAuth = getAuth(firebaseApp);
this.database = this.firebaseApp.database();
// database ref code here...
}
}
and it throws the following error:
return app.container.getProvider(name);
TypeError: Cannot read property 'getProvider' of undefined
If I remove "firebaseApp" from the getAuth(..) call I get this error:
No Firebase app '[DEFAULT'] has been created - call Firebase
App.initializeApp() (app/no-app)
However the "console.log("App Name...")" line produces:
App name=[DEFAULT]
So clearly a DEFAULT app has been created. Additionally if I remove the "getAuth..." call the database calls pulling data from the realtime database below it work just fine, which seem to imply the authentication worked properly because I can access data from the database.
What the heck is going on?
You are confusing Firebase Admin SDK (Node.js) with Firebase Javascript SDK. The former is for the back-end, while the latter is for the front-end. I understand your confusion because the front-end package/s are installable via NPM, although they are meant to be bundled with front-end code.
You can't do this:
import admin from 'firebase-admin' // back-end code
import { getAuth } from 'firebase/auth' // front-end code !!!
const adminApp = admin.initializeApp(...)
getAuth(adminApp) // TypeScript actually catches this error
/*
Argument of type 'App' is not assignable to parameter of type 'FirebaseApp'.
Property 'automaticDataCollectionEnabled' is missing in type 'App' but required in type 'FirebaseApp'.ts(2345)
app-public.d.ts(92, 5): 'automaticDataCollectionEnabled' is declared here.
const adminApp: admin.app.App
*/
If you are on the back-end, just use adminApp.auth() to get the Auth instance. If on the front-end, you need to call getAuth with the front-end Firebase App instance:
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
const app = initializeApp(...)
const auth = getAuth(app)
The new modular apis have a slightly different syntax. The following should still work if you wrap it in a class, but as long as you only do this once at the top of your express? server you shouldn't need to use a class.
Also, I'm using the require syntax but imports should work too depending on your setup.
//Import each function from the correct module.
const { initializeApp, applicationDefault } = require("firebase-admin/app");
const { getAuth } = require("firebase-admin/auth");
const { getDatabase } = require("firebase-admin/database");
const app = initializeApp({
credential: applicationDefault(), //Don't forget to export your configuration json https://firebase.google.com/docs/admin/setup
databaseURL: "https://DATABASE_URL",
});
const auth = getAuth(app)
const database = getDatabase(app)
It's not super well documented but you can find hints in the Admin SDK reference: https://firebase.google.com/docs/reference/admin/node/firebase-admin.auth
One tip: In VSCode you should see the a description of each function when you hover over them, if you have the import path formatted correctly.

Problem using a npm package in React - says "TypeError: require is not a function"

I'm trying to use the package lastfm within a React app.
I have installed it with
npm install lastfm
The official doc says it should be used like this :
var LastFmNode = require('lastfm').LastFmNode;
var lastfm = new LastFmNode({
api_key: 'abc',
secret: 'secret'
});
And this is how I use it in my React code :
import {LASTFM_API,LASTFM_API_SECRET} from "./Constants";
import {LastFmNode} from 'lastfm';
export class Lastfm {
static scrobbleTrack(track): void {
var lastfm = new LastFmNode({
api_key: LASTFM_API,
secret: LASTFM_API_SECRET,
useragent: 'appname/vX.X MyApp'
});
}
}
Which fires this error (from the package) :
TypeError: require is not a function at lastfm-request.js:3
I'm quite new to React and NPM.
I wonder if there is some kind of incompatibility ?
How could I make this work ?
Thanks !
The package is to be used on Node server and not on React App.
EDIT
Hi, sorry i cannot comment because my points are less.
You can not use that one as well because that is also a node package. If you see a syntax where you have to use: require('something'); usually means it is a node package because in React, your syntax for importing is something like this: const abc from 'xyz';

Can't use import syntax Error while importing uuid

I am trying to import uuid like
import { v1 as uuidv1 } from 'uuid';
But I get a syntax error
Cannot use import statement outside a module
because nodejs doesn't support BABEL!
try:
const { v1 as uuid} = require('uuid');
If you need BABEL you must add it and enable it: look this:
https://dev.to/ganeshmani/configuring-babel-for-node-js-express-server-35hp
or google it.

React Redux - Error passing several store enhancers to createStore()

I have a react app running redux and thunk which has all been working fine. I need to persist the store state on page reload so that data is not lost, so have created a function which is storing data in the localstorage and then returning the data ready for adding to createStore (https://stackoverflow.com/a/45857898/801861). The data storage is working fine and returning the object ready for setting the sate. When adding the data object at createStore react fails to compile with this error:
Error: It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function
Here is CURRENT CODE RETURNING ERROR:
const store = createStore(reducers, LoadState, applyMiddleware(thunk) );
//Error: It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function
My original code which was running:
const store = createStore(reducers, applyMiddleware(thunk) );
I attempted to fix this following some similar issues I found online, compiles but breaks site code which was originally working fine:
const composeEnhancers = LoadState || compose;
const store = createStore(reducers, composeEnhancers( applyMiddleware(thunk) ) );
//Error: Actions must be plain objects. Use custom middleware for async actions.
Not sure what I need to change to get this to work, any help is appreciated.
I think you are following a tutorial which is performing tasks in a previous version of redux.
You need to create a composeEnhancer which will take in your Redux Dev Tools extension as shown
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
after importing compose from 'redux' obviously as shown -
import {createStore, compose, applyMiddleware} from 'redux';
and then, you can create the store as shown -
const Store = createStore(rootReducer, composeEnhancer(applyMiddleware(thunk)))
The error is self-explanatory. It tells you what to do exactly!!
Namely it tell you that you should compose your enhancers instead.
Here is how to it:
Step #1: Import 'compose' from redux library
import { createStore, applyMiddleware, compose } from 'redux';
Step #2: Compose your list of enhancers since you have more than one
const enhancers = [LoadState, applyMiddleware(thunk)];
const store = createStore(
reducers,
compose(...enhancers)
);
Refer to this page for more details.
I suspect your issue is within your LoadState. What ever is it? Here is a working createStore:
const store = createStore(
reducers,
{ counter: { count: 5 } },
applyMiddleware(() => dispatch => {
console.log('Yoyoyo')
return dispatch;
}));
Hope it solves your issue. Make sure to put actual initial state values and not some function or what ever it is LoadState is :)
You can use a package to persist the redux store into the local storage and you don't need to make your own function:
https://github.com/rt2zz/redux-persist
In the first example of the package you can see how to use the persistReducer() and persistStore() to save your state and then auto rehydrates on refresh page.
plz check this advanced store setup that may help you
enter link description here
https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup
import { createStore, applyMiddleware, compose } from 'redux';
+ const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
+ const store = createStore(reducer, /* preloadedState, */ composeEnhancers(
- const store = createStore(reducer, /* preloadedState, */ compose(
applyMiddleware(...middleware)
));
Am starting out with it React-Redux and faced the same issue. am not sure if it is the right approach but here we go.
the one issue you only need to fix in your code is to call the function,
store = createStore(reducers, LoadState(), applyMiddleware(thunk) );
this solution worked for me.
For redux saga users,
import createSagaMiddleware from "redux-saga";
const sagaMiddleware = createSagaMiddleware();
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(rootReducer, composeEnhancer(applyMiddleware(sagaMiddleware)))
import { applyMiddleware, compose, createStore } from "redux";
import { devToolsEnhancer } from "redux-devtools-extension";
import { logger } from "./middlewares/logger";
import reducers from "./reducers";
import { todoReducer } from "./todoReducer";
const store = createStore(
reducers,
compose(applyMiddleware(logger), devToolsEnhancer({ trace: true }))
);
export default store;

Router is not defined in KOA2

I have two files, one of them is the app.js and the otherone is api.js.
In the first file I have :
app.use(setHeader)
app.use(api.routes())
app.use(api.allowedMethods())
And in api.js I have:
import KoaRouter from 'koa-router';
const api = new Router();
//Validatekey
const validateKey = async (ctx, next) => {
const { authorization } = ctx.request.headers;
console.log(authorization);
if (authorization !== ctx.state.authorizationHeader) {
return ctx.throw(401);
}
await next();
}
api.get('/pets', validateKey, pets.list);
When I run the project a error message is throw: Router is not defined.
But If I write both files together, the application go fine.
Anybody knows the problem?
I have solved with var Router = require('koa-router')
The import is currently not implemented in nodejs, neither is it supported in the latest ES2015(ES6).
You will need to use a transpiler like Babel to use import in code.I advice that avoid transpiler as it cause performance issues on production just go with require and it will work.
Obviously Nodejs does not support import / export syntax and using require will solve your problem.
However it is possible to make import work on Node.js by using babel transformers.
Look the following answer for more information https://stackoverflow.com/a/37601577/972240

Resources