Search code examples
javascriptnpmnpm-package

How to import npm package to a client file


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?


Solution

  • 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.