nuxt-modules / algolia

πŸ”Ž Algolia module for Nuxt
https://algolia.nuxtjs.org/
MIT License
189 stars 35 forks source link

Can't build project with v1.4.0 – `Agent` is not exported #119

Closed lukaszflorczak closed 1 year ago

lukaszflorczak commented 1 year ago
WARN  Error when using sourcemap for reporting an error: Can't resolve original location of error.                                                                                                                                                                                                                                                        

ERROR  'Agent' is not exported by __vite-browser-external, imported by node_modules/.pnpm/@algolia+requester-node-http@4.14.2/node_modules/@algolia/requester-node-http/dist/requester-node-http.esm.js                                                                                                                                                   
file: /Users/lukaszflorczak/my-project/node_modules/.pnpm/@algolia+requester-node-http@4.14.2/node_modules/@algolia/requester-node-http/dist/requester-node-http.esm.js:2:9
1: import * as http from 'http';
2: import { Agent } from 'http';
            ^
3: import * as https from 'https';
4: import { Agent as Agent$1 } from 'https';

Version

@nuxtjs/algolia: v1.4.0 nuxt: v3.0.0

Baroshem commented 1 year ago

Hey @lukaszflorczak

Thanks for raising this issue. I just found a workaround for that. It seems that Vite is managing to correctly serve server packages in dev environment while it breaks for production environment.

I will publish a new version in few minutes so that you could try if it fixes the issue.

Baroshem commented 1 year ago

It should be working now with 1.4.2 verions

lukaszflorczak commented 1 year ago

It works now. Thank you for the quick fix!

lukaszflorczak commented 1 year ago

Unfortunately, I have to reopen. The build completes without errors, but then the project fails to start.

Listening http://[::]:3000
(node:88372) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
[nuxt] [request error] [unhandled] [500] Unexpected token 'export'
  at internalCompileFunction (node:internal/vm:74:18)  
  at wrapSafe (node:internal/modules/cjs/loader:1141:20)  
  at Module._compile (node:internal/modules/cjs/loader:1182:27)  
  at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)  
  at Module.load (node:internal/modules/cjs/loader:1081:32)  
  at Module._load (node:internal/modules/cjs/loader:922:12)  
  at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:167:29)  
  at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
Baroshem commented 1 year ago

Hmm, strange. Could you share how do you use the module? Is it like an empty project or is it something more advanced?

lukaszflorczak commented 1 year ago

It's more advanced... But I had no problems with < v1.4.0.

In the app components I use:

const { result, search } = useAlgoliaSearch(ALGOLIA_INDEX)

// ...

And I also have API endpoint to store data in search index. But in this case I use algolisasearch directly:

const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_ADMIN_API_KEY)
const index = client.initIndex(ALGOLIA_INDEX)

try {
  await index.saveObjects(/* ... */)
} catch (err) {
  /* ... */
}    
Baroshem commented 1 year ago

I am especially interested in the first part because this is where these issues can be caused.

The second one does not seem to be causing these problems.

lukaszflorczak commented 1 year ago

Ok. So I have an input. And here is the code of the component:

const query = ref('')

// Filters
const level = useCookie('search:filter:level', { default: () => null, maxAge: 60 * 24 * 365 })

// Pending state
const pending = ref(false)
watch([query, level], ([query]) => pending.value = query?.length >= 2)

// Searching
const { ALGOLIA_INDEX } = useRuntimeConfig().public
const { result, search } = useAlgoliaSearch(ALGOLIA_INDEX)

watchDebounced([query, level], async ([query, level]) => {
  if (!query || query.length < 2) return

  await search({ query, requestOptions: { facetFilters: [level ? `levels:${level}` : ''] } })

  // If no results, try search again without level filter
  if (!result?.value.hits.length && level) {
    await search({ query })
  }

  pending.value = false
}, { debounce: 500, immediate: true })

Tomorrow I can try to reproduce it and share it with you.

Baroshem commented 1 year ago

Please do. I just ran a nuxt project with Algolia module in several cases in prod config and I couldnt reproduce it. Could you try to remove the module and see if the error occurs?

lukaszflorczak commented 1 year ago

For now, I checked that the project starts when I remove the module from nuxt.config.ts (of course the search engine doesn't work). The project works fine in dev mode. Now I'm trying to reproduce the error on a clean project.

UPDATE: Uh... I can't reproduce it πŸ€” @Baroshem Do you have any idea what I can do and where to look for the error?

Baroshem commented 1 year ago

Could you create a stackblitz link with repro? I might take a look at it once it is reproducable as for now I cannot reproduce it no matter how hard I try.

Baroshem commented 1 year ago

@lukaszflorczak any news regarding your issue?

lukaszflorczak commented 1 year ago

Sorry, I've been a bit busy. Today I will try to share with you in some way the project where I have this error.

lukaszflorczak commented 1 year ago

@Baroshem I created a repo with the reproduction: https://github.com/lukaszflorczak/nuxt-algolia-playground

If you run nuxt dev – it should works. The problem starts after nuxt build & nuxt preview.

I found that the problem is when both modules: @nuxtjs/algolia and @nuxtjs/supabase are active. My project is powered by Supabase and Algolia and I use them in production mode without any problems (versions: @nuxtjs/supabase@0.3.0 & nuxtjs/algolia@1.3.1).

Baroshem commented 1 year ago

I have finally managed to reproduce it. It seems that the following line is causing the issue with Supabase module. Dont really know why because it is a simple registration of the aliases but it may be connected to how Supabase is registering optimizeDeps. I will investigate it further and let you know.

// module.ts

extendViteConfig((config) => {
      config.resolve = config.resolve || {};
      config.resolve.alias = config.resolve.alias || {};
      config.resolve.alias = {
        ...config.resolve.alias,
        "http": "rollup-plugin-node-polyfills/polyfills/http",
        "stream": "rollup-plugin-node-polyfills/polyfills/stream",
        "util": "rollup-plugin-node-polyfills/polyfills/util",
        "process": "rollup-plugin-node-polyfills/polyfills/process-es6",
        "events": "rollup-plugin-node-polyfills/polyfills/events",
        "url": "rollup-plugin-node-polyfills/polyfills/url",
        "querystring": "rollup-plugin-node-polyfills/polyfills/qs",
        "https": "rollup-plugin-node-polyfills/polyfills/http"
      };
    });
lukaszflorczak commented 1 year ago

Thanks. I hope that we will be able to solve the problem soon :)

Baroshem commented 1 year ago

If I remove this extend config, both modukes work correctly.

So basically, to resolve both the initial problem and the problem you have right now @lukaszflorczak, we need to find a better way to work with node dependencies in Nuxt, without usage of the polyfill.

Baroshem commented 1 year ago

@pi0 here πŸ˜‰

pi0 commented 1 year ago

Checking with the reproduction @Baroshem provided, it seems vite is eagerly scanning dynamic import without checking the process.env guard (tree-shaking after)

Probably best solution would be providing nuxtApp.$algolia.transporter.requester polyfill using a server-only nuxt plugin in algolia.server.ts instead of here

An easier solution is mocking the @algolia/requester-node-http alias for client-build only.

"vite:extendConfig"(config, { isClient }) {
      if (isClient) {
        config.resolve.alias["@algolia/requester-node-http"] =
          "unenv/runtime/mock/empty";
      }
    },

Fixed sandbox: https://stackblitz.com/edit/github-epeint-mjbn5m?file=nuxt.config.ts

Baroshem commented 1 year ago

Thanks @pi0 for help!

I have tested it and it seems to be working. I have released a new 1.5.0 version with some other updates as well.

@lukaszflorczak could you test whether an issue is there for you when you bump to 1.5.0?

lukaszflorczak commented 1 year ago

It looks like everything is OK now. Thank you!

Baroshem commented 1 year ago

Awesome!

Sorry that it took so long.

If you will have any ideas on improving the module, let me know :)

lukaszflorczak commented 1 year ago

No problem ;) Algolia is the main engine of one of my applications, so with the development, there will probably be some more ideas

michaelvcolianna commented 1 year ago

Hello & apologies for bumping this but I'm experiencing the same error as the original ticket w/Nuxt 3.0.0 and @nuxtjs/algolia 1.5.1 (Agent is not exported). I tried the config change in https://github.com/nuxt-modules/algolia/issues/119#issuecomment-1384190558 as well, but that didn't fix. npm run dev works but neither npm run build / npm run generate works, and my project won't deploy to Netlify for the same reason.

Please advise if it would be better for me to open a new bug. I'm happy to provide code though all I have is the example under "client side" in the docs and I didn't want to paste a bunch of things here before I knew whether bumping/new bug was better. Thanks in advance!

Baroshem commented 1 year ago

Hey @michaelvcolianna

No worries. Please create a separate issue with your reproduction details (ideally some reproduction link on stackblitz) and I will take a look at it :)