4

How do I use a dependency in my javascript after I install it using npm? I just used NPM to install Fuse.js. npm install fuse.js

Then the website says to use the program I just have to add the following code and it will work:

var books = [{
  'ISBN': 'A',
  'title': "Old Man's War",
  'author': 'John Scalzi'
}, {
  'ISBN': 'B',
  'title': 'The Lock Artist',
  'author': 'Steve Hamilton'
}]

var options = {
  keys: ['title', 'author'],
  id: 'ISBN'
}
var fuse = new Fuse(books, options)

fuse.search('old')

But I keep getting console error Fuse is not defined. for the code var fuse = new Fuse(books, options) How do I get fuse defined after I do npm install?

I tried this site from node, and added require('Fuse') but that did not help. I continued to get the same error.

Vipin Kumar
  • 6,441
  • 1
  • 19
  • 25
Whitecat
  • 3,882
  • 7
  • 48
  • 78

2 Answers2

3

Node.js provide isolation of modules. If you want to use any package/dependency then you need to import it. Node.js follow commonJS module pattern so you need to add following line before using var fuse = new Fuse(books, options)

var Fuse = require('fuse.js')

It's a good practice to add this line on top of your file.

Vipin Kumar
  • 6,441
  • 1
  • 19
  • 25
2

You need to import the Fuse class before you can use it.

I think you can do that using something like this:

import Fuse from "fuse.js"
Titus
  • 22,031
  • 1
  • 23
  • 33