vite-plugin-node-polyfills icon indicating copy to clipboard operation
vite-plugin-node-polyfills copied to clipboard

Bug: importing 'crypto' polyfill leads to error `exports is not defined` with yarn build && yarn preview in nuxt

Open clangenb opened this issue 10 months ago • 7 comments

The following commit breaks yarn build && yarn preview: https://github.com/integritee-network/incognitee-campaign-page/commit/87272d0e60ae30cef384cc87b2918249a0073938.

However, unlike https://github.com/davidmyersdev/vite-plugin-node-polyfills/issues/90, I can't opt out of crypto as I need its function.

The code runs fine with yarn dev.

clangenb avatar Apr 30 '24 15:04 clangenb

@clangenb did you find any solutions for this? I am encountering this as well.

Mallfurion avatar May 20 '24 08:05 Mallfurion

I finally re-implemented our rsa crypto with the webcrypto api, so we don't need any polyfills at all. I would recommend such an approach if it is feasible in your case.

clangenb avatar May 20 '24 08:05 clangenb

same issue , any idea?

anton-liam avatar Jul 15 '24 06:07 anton-liam

I can only repeat what I mentioned above. If the crypto polyfill is needed because of a 3rd party dependency, I recommend looking for another dependency, as most maintained libraries should have switched to use the WebCrypto Api. If it is because of your own code (like in my case), I suggest rewriting the crypto stuff with WebCrypto API as I did here https://github.com/encointer/encointer-js/pull/101, with a follow-up fix in https://github.com/encointer/encointer-js/pull/105.

clangenb avatar Jul 15 '24 07:07 clangenb

@clangenb I can't rewrite the code because it's subpackage dependent.

After two hours of code retracing I found that the crypto-broserify dependent randomfill package was not transpiled by rollup.

sourcecode: randomfill:L39

the Error: image

Does that mean exports can't work with if by rollup?

anton-liam avatar Jul 15 '24 08:07 anton-liam

I am not an JS expert, but I would assume that this is a bug in either browserify or randomfill and that this should work in general.

clangenb avatar Jul 15 '24 09:07 clangenb

I used the replace plugin to change the code in question,

nuxt.config.ts

import { replaceCodePlugin } from 'vite-plugin-replace';

...
vite: {
    plugins: [
      replaceCodePlugin({
        replacements: [
          {
            from: `if ((crypto && crypto.getRandomValues) || !process.browser) {
  exports.randomFill = randomFill
  exports.randomFillSync = randomFillSync
} else {
  exports.randomFill = oldBrowser
  exports.randomFillSync = oldBrowser
}`,
            to: `exports.randomFill = randomFill
exports.randomFillSync = randomFillSync`,
          },
        ],
      }),
}

anton-liam avatar Jul 15 '24 10:07 anton-liam