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

Having trouble integrating a custom button into the toolbar of the Tinymce Vue.js wrapper

Struggling to add a custom button to the toolbar of tinymce using the vue.js wrapper (utilizing vue 3 and tinymce 5). The problem is that the custom button is not appearing in the toolbar. I have attempted the following steps, the logs in the init and set ...

What is the best way to achieve a Clamp-To-Border effect on a Texture loaded onto an Image in the THREE.js?

My scene includes a plane with an image loaded onto the texture. I've found that there is no Clamp-To-Border option for textures, only Clamp-To-Edge, Repeat Wrapping, and Mirrored Wrapping. Below is an image displaying the default ClampToEdge effect. ...

Can someone provide guidance on utilizing the index correctly within this v-for to prevent any potential errors?

I am encountering an issue with using index in a v-for loop to implement a function that deletes items from an array. The linter is flagging "index is defined but never used" as an error. I am following the instructions provided in a tutorial, but I am un ...

Navigating through objects to retrieve internal object values

I currently have a collection of objects stored in my program. const objs = { "1":{ "name":"Candice", "Classes": [00029,00023,00032,000222], "id":0002918 }, "2":{ "name":"Clark", "classes" ...

Injection of Angular state resolve into controller fails to occur

I'm attempting to ensure that the value from ui-router's resolve is successfully passed to the controller portalsForUserCtrl. Take a look at the router code below: (function () { 'use strict'; var myApp = angular.module("myApp", ["co ...

What does the underscore before a function in JavaScript or PHP signify?

I am curious about the significance of the underscore symbol (_) when it is placed before a function or variable. Does it serve to simply describe something, or is it required for executing specific functions or calling certain methods? In JavaScript: va ...

Unable to append DOM element using the node.insertBefore() method

I am facing an issue with a sorted list of items displayed alphabetically. My intention was to insert a corresponding letter from the alphabetArr array after each <li> element, using an id from the DOMElementsArr array. However, I seem to be missing ...

Is the UUID key displayed as an object within a Reactjs prop?

Hey there internet pals, I've stumbled upon a mysterious corridor, so dark that I can't see where I'm going.. could really use someone's flashlight to light the way. I have put together a basic, no-frills to-do list program. It consi ...

Preserve the authentic picture along with a blur mask that can be dragged and applied to it

Is there a way to preserve the original image while having a draggable blur mask over it? If you want to see an example of a draggable blur mask over an image, you can check out this link: https://codepen.io/netsi1964/pen/AXRabW $(function() { $("#ma ...

Numerous traditional commits of the `feat` type have been recorded on a single feature

I've recently joined a repository that leverages semantic-release for automating version updates of the NPM package. The repository follows the guidelines set by the Conventional Commits specification, however, the README is quite limited. If I creat ...

Investigate duplicate elements within nested arrays using the 3D array concept

I am dealing with an array that contains 3 subarrays. Arr = [[arr1],[arr2],[arr3]] My task is to identify and store the duplicate values found in these subarrays ([arr1],[arr2],[arr3]) into a separate array. Arr2 = [ Duplicate values of arr 1,2,,3 ] What ...

Using Vue.js to send user input data to a different page and trigger a method for submission

I am seeking assistance with my first question and hope to receive your support. In my setup, I have a catalogue page that includes a keyword search function and a main page with a search bar. My objective is to automatically redirect any submission from ...

The error message "Trying to call zmq.zmqVersion as a function, but it's not a function" occured while attempting to import the ZeroMQ

My current project involves creating a react app that can subscribe to an IPC socket using JavaScript code. I chose to use npx create-react-app for this purpose. To handle the subscription, I decided to utilize the npm package zeromq. However, when instal ...

ajaxStop and ajaxStart not functioning as expected

Currently working on a project to create a Wikipedia viewer, and running into an issue with the following code snippet: $(document).ready(function() { $(document).on('click', '#search_button', function() { ...

The program encountered an error: Unable to locate the module 'chart.js' in the directory '/node_modules/ng2-charts/fesm2015'

Having trouble with this error message: ERROR in ./node_modules/ng2-charts/fesm2015/ng2-charts.js Module not found: Error: Can't resolve 'chart.js' in /node_modules/ng2-charts/fesm2015' I ran the command "npm install --save ng2-chart ...

Error: NextJS cannot access the 'map' property of an undefined object

Hey everyone, I usually don't ask for help here but I'm really struggling with this piece of code. I've tried looking at various resources online but can't seem to figure out why it's not working. Any guidance would be greatly appr ...

Encountering a hurdle: Unable to run npm run dev in Next.js due to NPM error

> @ dev C:\Users\Mustafa\Desktop\React&Next\insta-2.0 > next dev 'Next\insta-2.0\node_modules\.bin\' is not recognized as an internal or external command, operable program or batch file. int ...

Implementing a Jquery check based on a checkbox

Hey, I'm having an issue with a condition. When I uncheck the checkbox, it doesn't uncheck. I've tried to make a block display, but the JavaScript isn't working. I attempted to add: document.getElementById("Reload").style.display = "b ...

Tips for retaining the value of a variable in JavaScript

I am a page that continuously redirects to itself, featuring next day and previous day arrows. Upon loading, the page always displays the new day. The days are stored in a localStorage as follows: for(var i = 0; i < status.length; i++) { local ...

Observable Knockout Dependency

I found an interesting example on the KnockoutJS site () and I want to implement something similar. My goal is to check if certain values are available on the client side when a category is selected. If they are not, then I need to fetch them from the ser ...