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?
CodePudding user response:
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";
CodePudding user response:
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!