Search code examples
javascriptreactjsjsxcryptojs

TypeError: CryptoJS is undefined


Im working on a project in ReactJS and I want to implement the AES function from CyptoJS library. But when I perform the event that triggers the use of the AES ecrypting I recieve the following error: TypeError: crypto_js__WEBPACK_IMPORTED_MODULE_1__.CryptoJS is undefined

import React, {useState} from 'react';
import {CryptoJS} from 'crypto-js';
export function Register(){
    var body = /* a JSON with information from the register */
    var encyMssg = CryptoJS.AES.encrypt(JSON.stringify(body), "key").toString();

    return(/* HTML COMPONENT*/);
}

The error displays in the var encyMssg line and this script is written in a .jsx file. Any kind of solution? Thank you for your time.

SOLVED thanks a lot. The problem as several of you said was the {} in the import line; the correcto way to import the libray was:

import CryptoJS from 'crypto-js';

Solution

  • Make sure you have to installed crypto-js using

    npm install crypto-js


    Then in your JS file import module you want to use.

    import aes from 'crypto-js/aes';

    Now you can aes like below.

    aes(value, key).toString()


    Here is working stackblitz example.

    React Crypto AES StackBlitz