nextapps-de / flexsearch

Next-Generation full text search library for Browser and Node.js
Apache License 2.0
12.53k stars 491 forks source link

Worker not working in production build #378

Open fhollste opened 1 year ago

fhollste commented 1 year ago

I've setup a worker with

new Document({
   ...
  worker: 1
})

Everything word fine in development but then trying to run a production build (Nextjs with webpack) I get an error `Error: Cannot find module '/Users/fredrik/dist/node/node.js'

This is most likely due to "../dist/node/node.js" not being part of the bundle.

Any ideas or workarounds for this?

vincesp commented 1 year ago

Seems to be this line: https://github.com/nextapps-de/flexsearch/blob/9abb781357f04e7db8529654c6941009771f4bf1/src/worker/index.js#L138

The first parameter for new Worker() is fileName which is a path relative to the current working directory. So above line only works if you start your script from a working directory inside of the flexsearch package.

vincesp commented 1 year ago

So here would be a workaround:

const path = require('node:path')
const { Worker } = require('flexsearch')

function createWorker() {
  const cwd = process.cwd()
  try {
    process.chdir(path.dirname(require.resolve('flexsearch')))
    return new Worker()
  } finally {
    process.chdir(cwd)
  }
}

const myWorker = createWorker()

Or with return new Document() accordingly.