TarekRaafat / autoComplete.js

Simple autocomplete pure vanilla Javascript library.
https://tarekraafat.github.io/autoComplete.js
Apache License 2.0
3.93k stars 236 forks source link

Error on constructor #280

Open massimiliamanto74 opened 2 years ago

massimiliamanto74 commented 2 years ago

I have a ts project with webpack. I have installed the package with npm: npm i @tarekraafat/autocomplete.js. I have add the library in my file: import { autoComplete } from "@tarekraafat/autocomplete.js"; I try to create a autocomplete using demo example:

const autoCompleteJS = new autoComplete({
      placeHolder: "Search for Food...",
      data: {
        src: [
          "Sauce - Thousand Island",
          "Wild Boar - Tenderloin",
          "Goat - Whole Cut",
        ],
        cache: true,
      },
      resultItem: {
        highlight: true,
      },
      events: {
        input: {
          selection: (event) => {
            const selection = event.detail.selection.value;
            autoCompleteJS.input.value = selection;
          },
        },
      },
    });

I receive this error: Uncaught TypeError: _tarekraafat_autocomplete_js__WEBPACK_IMPORTED_MODULE_0__.autoComplete is not a constructor

folknor commented 2 years ago

autoComplete.js is compiled as an umd module, which means webpack sometimes gets confused. There's a few silly things you can try;

const autoComplete = require("@tarekraafat/autocomplete.js")
const autoComplete = require("@tarekraafat/autocomplete.js/dist/autoComplete")
import { autoComplete } from "@tarekraafat/autocomplete.js/dist/autoComplete"
import { autoComplete } from "@tarekraafat/autocomplete.js/src"

I use the last one. But I don't use webpack, I use parcel nightlies.

Or you need to use library: { type: 'umd' } }: https://webpack.js.org/guides/author-libraries/#expose-the-library

https://jameshfisher.com/2020/10/04/what-are-umd-modules/ https://stackoverflow.com/questions/50435253/webpack-imported-module-is-not-a-constructor