Search code examples
javascripthashcryptojssha

TypeError: CryptoJS.SHA256 is not a function


import * as CryptoJS from 'crypto-js';
import * as ecdsa from 'elliptic';
import * as _ from 'lodash'

class Transaction {
    id = null;
    constructor(id, txIns, txOuts) {
        this.id = id;
        this.txIns = txIns;
        this.txOuts = txOuts;
    }
}

function getTransactionId (Transaction)
{
    const txInContent = Transaction.txIns.txOutId + Transaction.txIns.txOutIndex;
//    const txInContent = Transaction.TxIN.map((TxIN) => TxIN.txOutId + TxIN.txOutIndex).reduce((a, b) => a + b, '');
    const txOutContent = Transaction.txOuts.amount + Transaction.txOuts.address;
//    const txOutContent = Transaction.TxOut.map((TxOUT) => txOut.amount + txOut.address).reduce((a, b) => a + b, '');

    return (txInContent + txOutContent).toString();
}


class TxIN {
    txOutId = null;
    txOutIndex = null;
    signature = null;

    constructor(txOutId, txOutIndex, signature) {
        this.txOutId = txOutId;         // Previous transaction ID
        this.txOutIndex = txOutIndex;
        this.signature = signature;     // Sender's signature
    }
}

class TxOUT {
    amount = null;
    address = null;

    constructor(amount, address) {
        this.amount = amount;     // Amount value of output
        this.address = address;   // Receiver's address
    }
}

let testOut = new TxOUT(10, "tb1****************************ntxt");

let testIn = new TxIN("tb******************************tntxt", 0, "gg")

let testTrans = new Transaction("1329***********************1e99ba8", testIn, testOut);


var test = 'GG';

console.log(test);
var t = CryptoJS.SHA256(test);

I am using the CryptoJS.SHA256() on my JavaScript project. But is shows the "TypeError: CryptoJS.SHA256 is not a function". And I've already import the 'crypto-js'. When I tried to log the crypto. I found the "SHA256: [Function (anonymous)]". But the TypeError cannot be solved. Is there something I make a mistake?


Solution

  • try these :

    npm install @types/node --save-dev to install NodeJS definitions

    npm install --save @types/crypto-js
    

    In tsconfig.ts file add the following:

    "files": [
    "./node_modules/@types/node/index.d.ts"
    ]
    

    Import the library where you want to use it with import

    import * as sha256 from 'crypto-js/sha256';
    

    or with speical import syntax

    import sha256 = require("crypto-js/sha256");