Skip to content
Advertisement

Window is undefined error, when loading node_module package in a component

I am trying to use pickr package ( a color picker library) in my nuxt.js app , at import time it is providing error called window is undefined

here is code:

<script>
import Pickr from '@simonwep/pickr/dist/pickr.min.js';

let pickr;

export default {
  name: "ColorPicker",
  mounted(){
    pickr = Pickr.create({
          el: '.test-picker',
          theme: 'classic',
          swatches: [
              'rgba(244, 67, 54, 1)',
              'rgba(233, 30, 99, 0.95)',
          ],
  
      });
  }
}
</script>

tried approaches

  • i made pickr package as a nuxt plugin added it to nuxt.config.js with mode:client
  • i made pickr package as a nuxt plugin added it to nuxt.config.js with ssr:false

but it did not work 😥

Advertisement

Answer

After struggles i came up with this approach and did work for me

<script>

let PickrInstance;

if(process.browser){
   PickrInstance = require('@simonwep/pickr/dist/pickr.min.js')
}

let  pickr;

export default {
  name: "ColorPicker",
  mounted(){
    pickr = PickrInstance.create({
          el: '.test-picker',
          theme: 'classic',
          swatches: [
              'rgba(244, 67, 54, 1)',
              'rgba(233, 30, 99, 0.95)',
          ],

      });
  }
}
</script>

10 People found this is helpful
Advertisement