I created a React app and I try to make a separate file for functions.
I required 'jwt-decode' library like that:
const jwt_decode = require("jwt-decode");
After that I used it like that:
const verifyToken = (token) => { console.log(jwt_decode(token)); };
And exported like that:
module.exports = { verifyToken };
When I tried to use it in my react page, I saw this error in the console:
Uncaught TypeError: jwt_decode is not a function
What I did wrong?
You need to require the default export:
const { default: jwt_decode } = require("jwt-decode");
const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
console.log(jwt_decode(token));
Expected output:
{ sub: '1234567890', name: 'John Doe', iat: 1516239022 }
Alternatively use import when type in package.json is set to module.
import jwt_decode from "jwt-decode";
It looks like you are trying to use CommonJS require syntax in a React app that is likely using ES6 import syntax.
Try changing your code to the following:
import jwt_decode from "jwt-decode";
const verifyToken = (token) => { console.log(jwt_decode(token)); };
export default { verifyToken };
And then in your React page, use:
import verifyToken from './path/to/your/file';
It works to me!
Related
I'm developing a REACT JS app and I've a doubt. If I have something that must not be taken as a dependency i usually put a let like in this case, where I'm initializing Firebase for my app:
import { initializeApp } from 'firebase/app';
import { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check';
let app = null;
const useInitializeFirebase = () => {
if (app) {
return;
}
app = initializeApp(window.FIREBASE);
initializeAppCheck(app, {
provider: new ReCaptchaV3Provider(window.RECAPTCHA_SITE_KEY),
isTokenAutoRefreshEnabled: true,
});
};
export default useInitializeFirebase;
The so exported hook is called within the main index.js file in this way:
const App = () => {
useInitializeFirebase();
...
}
So if the hook gets called multiple times (e.g. for a re-render), Firebase won't give error.
Is this the best approach? Or maybe I should use useRef or useState or even something else?
EDIT
The problem occurs also if I don't use an hook.
Take this code as reference:
import { initializeApp } from 'firebase/app';
let firebaseApp = null;
export default (firebaseConfig) => {
if (firebaseApp === null) {
firebaseApp = initializeApp(firebaseConfig);
}
return firebaseApp;
};
That can be used in this way
import { getAuth, signInWithCustomToken } from 'firebase/auth';
import firebaseApp from '#Src/helpers/firebaseApp';
const firebaseLogin = (token) => {
const auth = getAuth(firebaseApp(window.FIREBASE));
return signInWithCustomToken(auth, token);
};
export { firebaseLogin };
In this way if I don't put a guard firebase would be initialized multiple times, giving error.
Recently i saw a video that i guy was exporting a module in commonjs:
// src/routes/index.js file
module.exports = [
require('./user'),
require('./auth'),
require('./demo')
]
// src/routes/user.js
const exppres = require('express')
const api = express.Router()
api.post('/user' , doSomething())
// src/handler.js
const express = require('express')
const api = require('./routes')
const app = express()
app.use(api) // add all routes
I tried all different ways of doing, like:
export default {
import "./user",
import "./auth"
}
and in server layer
import api from './routes'
but nothing works...
Someone knows how to do it?
Try this
module.exports = {
user:require('./user'),
auth:require('./auth'),
demo: require('./demo')
}
Then access them like this
const {user,auth, demo} = require("path to the expoted module")
I don't quite understand what you mean by "for its side effects only", because then you wouldn't need to export anything. Importing for side effects only is done like this with ES6 modules:
import './user';
import './auth';
import './demo';
If you wanted to re-export something from these modules, you'd typically write
export * from './user';
export * from './auth';
export * from './demo';
or
export { default as user } from './user';
export { default as auth } from './auth';
export { default as demo } from './demo';
You would not export an array.
I have problems with Laravel + Vite + Vue 3 project.
I have installed everything as documentation and needed, and this project works separated from Laravel and Vite. But here is the problem, TypeScript doesn't recognize export default. It's always giving an error like:
MainLayout.vue:42
Uncaught SyntaxError: The requested module '/resources/scripts/composable/Auth.js' does not provide an export named 'default' (at MainLayout.vue:42:1)
But the Auth.ts file has exported function, and it looks like:
export default function useAuth(){
return {
CurrentUserToken: 'test';
};
}
This is how I'm calling in some files (example)
import useAuth() from './Auth';
const { CurrentUserToken } = useAuth();
return CurrentUserToken;
Why it would not recognize this named function?
You can export it like this
export function useAuth() {
return {
CurrentUserToken: 'test';
};
}
Import
import { useAuth } from './Auth';
Execute the function
useAuth();
OR
If you want to export default
export default function() {
return {
CurrentUserToken: 'test';
};
}
And import would look like this
import useAuth from './Auth';
Execute the function
useAuth();
I'm having an issue with a linting error in a vue.js project. The error that I get looks like this:
/Users/mikecuddy/Desktop/coding/data_science_projects/statues/client/src/store/modules/common.js
4:1 error Dependency cycle via #/store/index:4 import/no-cycle
I have no idea how to get rid of this error. I tried renaming files, using this.$router and this.$store with no luck. Here is some of my code:
router -> index.js:
The data path is the main one I want to get to. Notice that I have the store import files commented out - that does get rid of the dependency error but then I have issues with doing something like:
this.$store.state.common.loginFlag
as opposed as importing the store and doing this:
store.state.common.loginFlag
import Vue from 'vue';
import VueRouter from 'vue-router';
// import store from '../store/index.js';
// import store from '#/store/index';
import Home from '../views/Home.vue';
Vue.use(VueRouter);
const routes = [
{
path: '/data',
name: 'Data',
component: () => import('../views/Data.vue'),
beforeEnter: (to, from, next) => {
if (this.$store.state.common.loginFlag === false) {
next('/login');
} else {
next();
}
},
beforeRouteLeave: (to, from, next) => {
if (this.$store.state.common.loginFlag === false) {
next('/login');
} else {
next();
}
},
},
];
const router = new VueRouter({
routes,
});
export default router;
store/modules/common.js:
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
import router from '../../router';
Vue.use(Vuex);
const data = {
userNotFound: false,
passwordNoMatch: false,
loginFlag: false,
};
const getters = {
userNotFound: (state) => state.userNotFound,
passwordNoMatch: (state) => state.passwordNoMatch,
loginFlag: (state) => state.loginFlag,
};
const actions = {
login: ({ commit }, { payload }) => {
const path = 'http://localhost:5000/login';
axios.post(path, payload)
.then((res) => {
if (res.data.login_flag) {
commit('session/setUserObject', res.data.user, { root: true });
commit('setLoginFlag', res.data.login_flag);
// Tried this:
router.push{ name: 'Data' }
// As well as trying this:
this.$router.push({ name: 'Data' });
}
commit('setNoPasswordMatch', res.data.Password_no_match);
commit('setUserNotFound', res.data.Not_found);
})
.catch((error) => {
console.log(error);
});
},
};
// I have mutations but did not think they'd be needed
const mutations = {};
export default {
namespaced: true,
state: data,
getters,
actions,
mutations,
};
In the common.js file I've tried commenting out:
import router from '../../router';
and that seemed to work - got the Dependency cycle error to go away and in the router/index.js file I was able to get to the route but had an issue with this.$store.state.common.loginFlag when I commented out import store from '#/store/index'; If I leave in the import of: import store from '#/store/index';
then I get the dependency cycle error.
I've also found some help at these other stack pages:
TypeError: Cannot read properties of undefined (reading '$router') vuejs
dependency cycle detected import/no-cycle
I will say that I hate using linters and that's what's giving me the problem here.
Here is the code for store/index.js:
import Vue from 'vue';
import Vuex from 'vuex';
import common from './modules/common';
import session from './modules/session';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
common,
session,
},
});
Looks like the reason for the dependency cycle here is when you are importing router setup in the store module, and the router in turn imports the whole store. It's okay to use store in router, but try to move routing/redirect logic (these lines):
// Tried this:
router.push{ name: 'Data' }
// As well as trying this:
this.$router.push({ name: 'Data' });
from /modules/common.js to the component or global router hook level, so you avoid router import in the store module.
I was under the impression that this syntax:
import Router from 'react-router';
var {Link} = Router;
has the same final result as this:
import {Link} from 'react-router';
Can someone explain what the difference is?
(I originally thought it was a React Router Bug.)
import {Link} from 'react-router';
imports a named export from react-router, i.e. something like
export const Link = 42;
import Router from 'react-router';
const {Link} = Router;
pulls out the property Link from the default export, assuming it is an object, e.g.
export default {
Link: 42
};
(the default export is actually nothing but a standardized named export with the name "default").
See also export on MDN.
Complete example:
// react-router.js
export const Link = 42;
export default {
Link: 21,
};
// something.js
import {Link} from './react-router';
import Router from './react-router';
const {Link: Link2} = Router;
console.log(Link); // 42
console.log(Link2); // 21
With Babel 5 and below I believe they have been interchangeable because of the way ES6 modules have been transpiled to CommonJS. But those are two different constructs as far as the language goes.
To do this:
import {purple, grey} from 'themeColors';
Without repeating export const for each symbol, just do:
export const
purple = '#BADA55',
grey = '#l0l',
gray = grey,
default = 'this line actually causes an error';
Except for different exports, it may also lead to
different bundled code by WebPack when using two variant ways to destruct ESM modules:
// react-router
export function Link(str) { /* ... */ }
Destruct within the import statement:
import {Link} from 'react-router';
Link('1');
Link('2');
// WebPack output
var util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
(0,util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__.Link)('1');
(0,util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__.Link)('2');
Use destructuring syntax:
import * as Router from 'react-router';
const {Link} = Router;
Link('1');
Link('2');
// WebPack output:
var util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
const {Link} = util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__;
Link(1);
Link(2);
As you can see in the output example above where there is redundant code, which is not good for optimization when trying to uglify via UglifyJS, or Terser.