Production build problem when using Cryptojs

Asked

Viewed 162 times

1

I have an application written in Angular 6 and there was a need to send a hash to the client. The contractor approved only the use of the library crypto-js. I did the implementation and everything works correctly on ng serve, but when making the production build it gives an error.

Procedure performed:

Installation of dependency on Crypto-ts and typings.

npm install crypto-js --save
npm install @types/crypto-js --save-dev

Use of Cryptojs

I make use of the crypto-js in a service Angular. I leave below the two ways I tried to use the library to fix the error.

// Primeira maneira
import * as CryptoJS from 'crypto-js';
console.log(CryptoJS.MD5('minha-string').toString());

// Segunda maneira
import { MD5 } from 'crypto-js';
console.log(MD5('minha-string').toString());

The error returned is Module build failed. As below:

ERROR in ./node_modules/crypto-js/core.js
Module build failed (from ./node_modules/@angular-devkit/build-optimizer/src/build-optimizer/webpack-loader.js):

The problem only occurs when executing the command ng build --prod

Has anyone ever been through it? How could it solve the problem?

Thank you.

  • vc added the library to the angular.json file?

  • So @Eduardovargas in the tutorials did not mention this, could explain how it is done?

  • https://github.com/angular/angular-cli/wiki/stories-global-scripts. take a look at this link and try to find the scripts property in your angular.json or angular-cli.json

  • @Eduardovargas tried to add the address ". /node_modules/Crypto-js/core.js" in the angular.json scripts as described and I still receive the same error

1 answer

1


After suffering a little I managed to solve my problem, I don’t think it was the best way. So if anyone has another solution for that I’ll be modifying the correct answer.

What I did to solve the problem:

First I went to the archive angular.json and added the scripts core.js and md5.js in my scripts. As below:

"scripts": [
    "./node_modules/crypto-js/core.js",
    "./node_modules/crypto-js/md5.js"
]

Heed: There are 2 places with key scripts, so modify in both places.

After that I modified my service at the angular as below:

import { Injectable } from "@angular/core";

declare var CryptoJS;
@Injectable()
export class HasherService {

     getMd5(str: string): string {
         return CryptoJS.MD5(str).toString();
     }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.