Home > Mobile >  How to import and use npm package in Ember.js?
How to import and use npm package in Ember.js?

Time:02-06

I am new to EmberJS and I want to import and use the crypto-js in my EmberJS app, I used ember install crypto-js to install the package, then add those lines in ember-cli-build.js to add them to ember build to use SHA256 function:

  app.import('node_modules/crypto-js/core.js');
  app.import('node_modules/crypto-js/crypto-js.js');
  app.import('node_modules/crypto-js/sha256.js');

And I can see that in browser, assets/node_modules has the crypto-js folder with above 3 files. However I still got Could not import module 'crypto-js' error. How to solve it? Thanks!

CodePudding user response:

There is no need for app.import.

As long as you have ember-auto-import installed, or you are using embroider (which defers to webpack), you can follow the documentation: https://www.npmjs.com/package/crypto-js

import sha256 from 'crypto-js/sha256';
import hmacSHA512 from 'crypto-js/hmac-sha512';
import Base64 from 'crypto-js/enc-base64';

CodePudding user response:

Create a file called crypto-js.js in the shims folder and add this code

import 'crypto-js/core';
import 'crypto-js/sha256';

export default window.CryptoJS;

In your ember-cli-build.js file, add this linne:

app.import('vendor/shims/crypto-js.js', { using: [{ transformation: 'cjs', as: 'crypto-js' }] });

in your component, controller or model, you can import the library and use the SHA256 function like this

import crypto from 'crypto-js';
const hash = crypto.SHA256("Message to hash");
console.log(hash.toString());
  • Related