skip to Main Content

I have tried to migrate a CRA to vite. One remaining obstacle is a dependency of a dependency that has this code:

var requestFrame = (function () {
  var window = this
  var raf = window.requestAnimationFrame ||
  //...and so on and so forth
})()

this is undefined and the first thing it tries to invoke (requestAnimationFrame) throws. The page, depending on a dependency that depends on this seems to have worked fine before so I’m suspecting that something can be configured in vite to fix this, but i’m not sure what to be looking for.

2

Answers


  1. Chosen as BEST ANSWER

    What seems to work for me and my particular case is to patch this one particular package with patch-package. I've made a diff that changes

    -  var window = this
    +  var window = typeof window !== 'undefined' ? window : (typeof global !== 'undefined' ? global : {});
    

    I have been able to do a fresh install after removing /node_modules and i've been able to build this inside docker. I guess i was always able to build it, it's just that now it actually works and does not crash some page.


  2. The issue arises because in strict mode (which Vite uses by default), this in an IIFE (Immediately Invoked Function Expression) is undefined. This was not the case in older versions of JavaScript or non-strict mode, where this would refer to the global object (e.g., window in browsers).

    I will suggest another solution, Just check:

    import { defineConfig } from 'vite';
    import replace from '@rollup/plugin-replace';
    
    export default defineConfig({
      plugins: [
        replace({
          preventAssignment: true,
          values: {
            'var window = this': 'var window = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this)'
          }
        })
      ]
    });
    

    here the var window = this So that it will work, please check

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search