weixsong / elasticlunr.js

Based on lunr.js, but more flexible and customized.
http://elasticlunr.com
MIT License
2.02k stars 147 forks source link

Facing this issue with importing elasticlunr TypeError: (0 , elasticlunr_1.default) is not a function #135

Open saran1856 opened 2 years ago

saran1856 commented 2 years ago

I'm trying to integrate elasticlunr library into my web component library. I'm using stencil and TypeScript for building web components. I'm trying to create index like this:

import elasticlunr from "elasticlunr";

// Create a sample search index for thread view rendering.
export const createThreadSearchIndex = (docs: any[]) => {
  const index = elasticlunr();

  // Set fields to index. we can even set
  index.addField("content" as never);
  // Set the field used to identify documents.
  index.setRef("id" as never);
  // include content data with the index data.
  index.saveDocument(true);

  // Add the docs to the index
  docs.forEach((doc) => index.addDoc(doc));

  return index;
};

But this approach doesn't seem to work as my unit tests are failing with the following error message:

TypeError: (0 , elasticlunr_1.default) is not a function

Now I can fix this by changing the import statement and bringing in elasticlunr using require. However, the issue is that now my components won't render in browser because it doesn't support require. My tsconfig file looks like this:

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "allowUnreachableCode": false,
    "declaration": false,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2017"
    ],
    "moduleResolution": "node",
    "module": "esnext",
    "target": "es2017",
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "checkJs": true,
    "jsx": "react",
    "jsxFactory": "h",
    "types": ["jest"],
    "typeRoots": [
      "index.d.ts",
      "./node_modules/@types",
    ],
  },
  "include": [
    "src"
  ],
  "exclude": [
    "node_modules",
    "*/*.stories.*",
  ]
}

Can anyone please help me out here? There is no guidance anywhere as to how to solve it.

larrystone commented 2 years ago

Here's my implementation. I hope you find it helpful.

import elasticlunr from "elasticlunr";

export const index = elasticlunr<Record<string, string | number>>(function () {
  this.addField("name");
  this.setRef("id");
});

You can also extend the index further and use across various files

import {index} from 'filepath';

index.addField('fieldName');

index.search('textToSearch');

...