Guide to importing an npm package into a client-side file

Having some trouble importing the js-search npm package into my client-side .js file. The documentation suggests using

import * as JsSearch from 'js-search';
, but I keep getting a
Uncaught TypeError: Failed to resolve module specifier "js-search". Relative references must start with either "/", "./", or "../".
. After trying different relative paths, I realized that 'js-search' actually refers to the package name and not the directory. Is there a missing dependency that I need to include in order to use this import statement? Thank you.

Edit: project directory structure:

myproject
├── myproject
├── node_modules\js-search
└── myapp
    ├── static\myapp
    │            └── myapp.js
    └── templates\search
                    └── index.html

Edit: Could it be related to running on localhost rather than a server?

Answer №1

It appears that the NPM package you're currently utilizing is designed for node.js code. The line

import * as JsSearch from 'js-search';
is specifically intended for node.js, and may not function properly on its own within a browser environment.

If you wish to use such packages in a browser setting, you will likely need to convert them using a transpiler. One of the most commonly used ones for this purpose is webpack.

Sometimes, packages include pre-built or minified versions tailored for browsers. If this is the scenario here, you might come across a file named something.min.js within the js-search directory.

It seems that js-search may offer this option, given that there's a rollup configuration file present in their repository. Rollup serves as an alternative to webpack in this regard.

If a pre-built version isn't available, you may find yourself delving into the complex realm of build tools to make it work within a browser environment.

Answer №2

To include your myapp.js file, ensure to use type="module" as shown below:

<script type="module" src="myapp.js"></script>

Within the myapp.js file, you must import js-search using a relative path from node_modules, especially if you are not utilizing a bundler such as webpack. In your myapp.js script, utilize js-search similarly to this example:

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]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Perform the same actions on every element within the ul li

I'm facing an issue with my unordered list, where each list item contains a span element with an image inside. My goal is to set the background-image of each span to be the same as the image it contains, while also setting the opacity of the image to ...

Need a place to keep your data safe while using nodejs?

I have taken on the task of developing a lastfm plugin for a chat bot that my friend created. One feature I want to include is the ability for users to register their hostmask/nick with their lastfm username (for example, using the command !reg lastfmuser ...

JavaScript date input formatting with HTML

When using the input date picker in HTML, the default format displayed is MM-DD-YYYY. <input type="date" id="gdatum" /> Is there any method to change the mask to DD-MM-YYYY? ...

Unveil as you scroll - ScrollMagic

I am working on a skill chart that dynamically fills when the document loads. I am exploring the possibility of using ScrollMagic to animate the chart filling as the user scrolls down. After trying various combinations of classes and pseudo-classes in the ...

The responsive class seems to be malfunctioning within the Laravel 5.3 framework

I have a project that involves Laravel and Vue.js. In my Laravel project, I am importing Bootstrap CSS using the following line: // Bootstrap @import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap"; This import is done in the app.scss file. ...

Implementing conditional color parameter using Vuetify on an element

In my Vuetify project, I'm utilizing the built-in color parameter and predefined colors. My goal is to dynamically change the component's color based on the data it receives. For example, if complete: true, then the color should be green. Here&a ...

Iterate through each row asynchronously, waiting for each one to complete before moving on to the

Trying to navigate through multiple pages using puppeteer has been successful, except when attempting to parse through them at the same time. The issue seems to stem from the code executing async operations in rapid succession, overwhelming the browser. My ...

What is the best way to implement autoplay sound on a JavaScript webpage?

I'm currently working on a web system aimed at monitoring values from a database, and I have the requirement to trigger a sound alert when a specific range of values is received. Despite trying various examples found online, none of them have been suc ...

What methods does MaterialUI utilize to achieve this?

Have you checked out the autocomplete feature in their component? You can find it here: https://mui.com/material-ui/react-autocomplete/ I noticed that after clicking on a suggestion in the dropdown, the input box retains its focus. How do they achieve thi ...

Unable to retrieve the parent element using jQuery

I am facing an issue with my html structure that is generated dynamically through a foreach loop. I have attempted to remove the entire <a> element by accessing it from its ACTIVE HYPERLINK. However, all my efforts seem to be in vain as I am unable t ...

Completed Animation with Callback in AngularJS CSS

Currently working with AngularJS and hoping to receive a notification upon completion of an animation. I am aware that this can be achieved with javascript animations such as myApp.animation(...), but I'm intrigued if there is an alternative method wi ...

Vue-resource is returning a Promise object

How do I access the response data in an Ajax call? When I log response.text(), it displays a PromiseObj. Console PromiseObj context: undefined promise: Promise {status: "resolved", result: ")]}',↵{\"Result\":\"SUCCESS\",&bs ...

pattern validation using a regular expression

I am just starting to learn about regular expressions. In my current project, I am allowing users to input amounts in both shorthand and full digit formats using a material UI TextField component. Here are some examples of the input formats: 400k - short ...

Using HTML and C# to Deliver Emails

I've encountered a challenge with my HTML page that includes a textbox for users to input their email. When the submit button is clicked, an email should be sent to a specific email address defined in the code, and a pop-up box indicating "Email Sent" ...

Exploring Methods for Retrieving offsetHeight and scrollHeight in AngularJS

I am currently developing a directive that requires three specific values: scrollTop offsetHeight scrollHeight projectModule.directive('scroller', function ($window) { return { restrict: 'A', link: function (scope, elem, attrs) { ...

Issue encountered when attempting to alter the action attribute of a form: receiving an error message stating 'undefined is not a function'

I am attempting to dynamically set the action attribute of a form based on the button clicked in order to navigate away from a page. Once the action is updated, the form should be submitted and the new action carried out. Below is my jQuery function: fun ...

Guide to updating 2 iframes simultaneously with a single link/button using HTML and JavaScript

Just joined the community and looking for help on how to refresh two different iframes within a single page. I came across a solution on Google that involves using getElementById. However, I've heard Firefox can be tricky with IDs. Appreciate any as ...

Having trouble getting `sudo apt install npm` to work? You might be encountering the error message "The following packages have unmet dependencies

Creating dependency tree Retrieving status information... Completed Certain packages could not be installed. This might indicate that you have requested an unrealistic scenario or if you are utilizing the unstable version, some necessary packages could s ...

If I change the request mode to 'no-cors' in my Firebase cloud function, how will it impact the outcome?

After encountering an issue with the Firebase inbuilt password reset functionality, I created a Firebase function to handle OTP verification and password changes based on the correctness of the OTP. The function is designed to validate the OTP provided, ch ...

Include a "remember me" feature in the Stripe form

I am currently working on an exciting project using Angular 6. Within my website, I have decided to integrate the Stripe payment system. However, I would like to incorporate a unique and default "remember me" feature offered by Stripe. <div id="card-e ...