squirrelly icon indicating copy to clipboard operation
squirrelly copied to clipboard

Uncaught ReferenceError: require is not defined in ViteJS

Open Kukunin opened this issue 3 years ago • 3 comments

Describe the bug The package includes require that causes an exception in a browser bundle built by ViteJS. It happens because of these lines:

https://github.com/squirrellyjs/squirrelly/blob/master/src/file-utils.ts#L1-L2

That file should be imported only in nodejs build, not a browser. At least, it should not be included in ESM format

Kukunin avatar Feb 23 '22 05:02 Kukunin

I was able to make it work via passing transformMixedEsModules: true to the commonJsOptions:

export default defineConfig({
  ...
  build: {
    commonjsOptions: {
      transformMixedEsModules: true
    },
  }
})

Background: https://stackoverflow.com/a/63099935/1574484

dahei avatar Mar 27 '23 11:03 dahei

To make this solution more visible for people with the same error, I want to add that this is happening with Sveltekit and the Netlify-adapter. @dahei’s solution added to vite.config.js worked for me.

jnsprnw avatar Apr 20 '23 16:04 jnsprnw

Another solution is to import the browser minified code instead of the regular export of the package when you're running this package in the browser :

import * as Sqrl from 'squirrelly/dist/browser/squirrelly.min.js'

lisilinhart avatar Nov 17 '23 10:11 lisilinhart