I'm in custom module for Drupal, and i need to use JWT in javascript.
So i tried npm i jsonwebtoken and import jwt from "../node_modules/jsonwebtoken/index.js"; on my js/index.js
But i have the following error : Uncaught SyntaxError: The requested module '../node_modules/jsonwebtoken/index.js' does not provide an export named 'default'
I dont understand what to do and how i can load my library jsonwebtoken.
Sorry i'm really a beginner in javascript.
When you import node modules you don't enter the relative path. You only put the name of the module your trying to import. Also the module dosnt have a default module which means you need to import everything into one variable or import specific functions.
If you use javascript you should use require instead of import. The example below is taken from their docs.
// reference https://www.npmjs.com/package/jsonwebtoken
var jwt = require('jsonwebtoken');
var token = jwt.sign('payload', 'secret');
// quick and dirty
import * as jwt from 'jsonwebtoken';
// This is the way you should do it
import {sign, decode, JsonWebTokenError, TokenExpiredError, verify, NotBeforeError} from 'jsonwebtoken'
I created an example.ts file and run the following commands.
npm i -s jsonwebtoken && npm i -D @types/jsonwebtoken
So my structure is somthing like this
Then I added those 2 lines to get the result below
import {sign} from 'jsonwebtoken';
sign('foo-bar', 'secret', undefined, ((err, res) => console.log(res)));
Console: eyJhbGciOiJIUzI1NiJ9.Zm9vLWJhcg.o2WiQrAIplX3gvloUOTaxCTlvmsWhFwxk9rh6xHoFs8