Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

static import works from nuxt.config.js but not from component

I have a vanilla js jsencrypt package which i needed to use in my nuxt application, the package itself works fine when imported from Nuxt.config.js but i run into issues when imported using the head object from component, let me show you my code

nuxt.config.js //this works

head: {
    title: 'App',
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ],
    script: [
      {
        src: "/js/jsencrypt.min.js",
        body: true
      }
    ],
  },

component call //this doesnt work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export default {

  head() {
      return {
        script: [
          {
             src: "/js/jsencrypt.min.js",
             body: true
          }
        ],
      }
    },
}

i am using the head tag which in theory should work but it doesn’t

mounted() function

mounted(){
    var encrypt = new JSEncrypt();
}

I get an error back

JSEncrypt is not defined

since this class is going to be used in encrypting only one component , registering it globally doesnt seem like a smart move, does anyone know what the problem is?

>Solution :

Pulling in JSEnquiry in your head tag will work just fine, but you need to allow time for it to download and parse. Calling it in the mounted hook doesn’t allow for that.

Try this in your mounted hook.

const onAvailable = (variable, callback) => {
  function checkVariableIsAvailable(variable, callback) {
    if (typeof window[`${variable}`] === 'undefined') {
      setTimeout(function() {
        checkVariableIsAvailable(variable, callback)
      }, 1)
    } else {
      callback()
    }
  }
  checkVariableIsAvailable(variable, callback)
}

onAvailable('JSEncrypt', () => {
  var encrypt = new JSEncrypt();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading