0

I have installed chancejs using the command below:

npm install chance

I have created an angular 10 project and cannot find any chance.js library added. When I try to use the chance methods such as chance.string() in the file employee.component.spec.ts, it says chance does not exist.

  var randomName = **chance**.string();

I have checked other tutorials where they are importing the script directly into the html component. But is there another way to import it as a Module in typescript?

avdeveloper
  • 449
  • 6
  • 30

2 Answers2

1

First solution:

import chance from 'chance';

var randomName = chance().string();

Second solution:

in scripts under build:

node_modules/chance/dist/chance.min.js

and

declare var Chance; // After imports in component/service etc.

var randomName = Chance().string();
Buczkowski
  • 2,296
  • 12
  • 18
  • The first version is preferable. Also, in the second version, the `declare var Chance` _**does not**_ need to be placed "After imports in component/service etc." – Aluan Haddad Aug 24 '20 at 11:35
  • @AluanHaddad I only meant to not put `declare var Chance` inside `class` but you are right. Why first version is preferable thought? – Buczkowski Aug 24 '20 at 11:49
  • 1
    Because it is a module, and importing it states the dependency and thereby causes loading/bundling/typechecking, improving maintainability and clarity (if a new version changes the directory structure of the distribution, you don't have to update a thing). Also, global variables are bad. That's why we have module systems and we should use them wherever possible. – Aluan Haddad Aug 24 '20 at 11:51
0

install chance in your angular project

npm i chance

and then import chance.min.js in your angular.json file.

"scripts": ["node_modules/chance/dist/chance.min.js"]

and then in your component declare chance in import section like this.

declare var Chance: any;

and in your class

export class component implements OnInit {
chance: any;
constructor() {
    this.chance = new Chance();
    console.log(this.chance.ip());
  }
}

after all these steps please restart your dev server. hope it will work. happy coding :)

Farhat Zaman
  • 1,339
  • 10
  • 20