Reputation: 387
I am trying to import the js-search npm package to my client .js
file. Their docs says to write import * as JsSearch from 'js-search';
, however, this gives me a Uncaught TypeError: Failed to resolve module specifier "js-search". Relative references must start with either "/", "./", or "../".
. I tried to configure a relative path for a long time, however I finally figured out that 'js-search'
refers to the package name, not the directory. So, I must be missing some dependency that allows me to use this import line? Thank you.
Edit: directory structure:
myproject
├── myproject
├── node_modules\js-search
└── myapp
├── static\myapp
│ └── myapp.js
└── templates\search
└── index.html
Edit: could it be because I'm running on localhost and not a server?
Upvotes: 6
Views: 15617
Reputation: 356
You have to link your myapp.js
file using type="module"
like below
<script type="module" src="myapp.js"></script>
and then in myapp.js
you have to import js-search
using relative path from node_modules
since you are not using any bundler like webpack. In your myapp.js
file you can use js-search
like below
import * as JsSearch from './node_modules/js-search/dist/esm/js-search.js';
var theGreatGatsby = {
isbn: '9781597226769',
title: 'The Great Gatsby',
author: {
name: 'F. Scott Fitzgerald'
},
tags: ['book', 'inspirational']
};
var theDaVinciCode = {
isbn: '0307474275',
title: 'The DaVinci Code',
author: {
name: 'Dan Brown'
},
tags: ['book', 'mystery']
};
var angelsAndDemons = {
isbn: '074349346X',
title: 'Angels & Demons',
author: {
name: 'Dan Brown',
},
tags: ['book', 'mystery']
};
var search = new JsSearch.Search('isbn');
search.addIndex('title');
search.addIndex(['author', 'name']);
search.addIndex('tags')
search.addDocuments([theGreatGatsby, theDaVinciCode, angelsAndDemons]);
console.log(search.search('The')); // [theGreatGatsby, theDaVinciCode]
console.log(search.search('scott')); // [theGreatGatsby]
console.log(search.search('dan')); // [angelsAndDemons, theDaVinciCode]
console.log(search.search('mystery')); // [angelsAndDemons, theDaVinciCode]
Upvotes: 5
Reputation: 99505
The NPM package you are using is likely a package made for node.js code. The import * as JsSearch from 'js-search';
line is intended for node.js, and will not work by itself in a browser.
To run these kinds of packages in a browser, you will need to basically convert it using a transpiler. The most common one probably being webpack.
Sometimes packages also include a pre-built or minified version in their package specifically for browsers. If this is the case, you might find a file like something.min.js
in the js-search
directory.
js-search
looks like it might have this, as I see a rollup configuration file in their repository. Rollup is an alternative to webpack.
If this is not the case, you unfortunately have to go down the pretty crazy rabbithole that is build tools.
Upvotes: 8