ajitid / fzf-for-js

Do fuzzy matching using FZF algorithm in JavaScript
https://fzf.netlify.app
BSD 3-Clause "New" or "Revised" License
881 stars 22 forks source link

Better support cjs #124

Open Pcrab opened 10 months ago

Pcrab commented 10 months ago

When I tried to use fzf in a commonjs package, it always throws

Error [ERR_REQUIRE_ESM]: require() of ES Module xxx/node_modules/.pnpm/fzf@0.5.2/node_modules/fzf/dist/fzf.umd.js from xxx/index.js not supported.
fzf.umd.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
Instead either rename fzf.umd.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in xxx/node_modules/.pnpm/fzf@0.5.2/node_modules/fzf/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

I've read https://github.com/ajitid/fzf-for-js/issues/85, if I change my package to esm, this can be solved, but the package must finally be compiled to a cjs format.

This can be fixed if the umd format dist file is renamed to fzf.umd.cjs since "type": "module" is added at the end of package.json.

changes to package.json

{
  "main": "./dist/fzf.umd.cjs",
  "exports": {
    ".": {
      "require": "./dist/fzf.umd.cjs"
    }
  }
}

changes to vite-legacy.config.ts

export default defineConfig({
  build: {
    lib: {
      fileName: (format) => `fzf.${format}.cjs`,
    },
  },
});
ajitid commented 10 months ago

Heya! I looked at your PR and I can't say for sure if it'll be accepted. I'll have to check in other projects to know if it is an actual convention or format to have .umd.cjs as extension. This will take longer than usual as I'm occupied with other things as well.