How to load a resource on the client side only in Nuxt.js

雨燕双飞 提交于 2019-12-11 18:33:57

问题


I'm trying to build an app using Tone.js on top of Nuxt.js. Tone.js requires the browser's Web Audio API and as Nuxt renders stuff on the server side my build keeps failing.

Nuxt addresses this in the plugin documentation and I've followed that approach in my nuxt.config.js file writing:

module.exports = {
  plugins: [{src: '~node_modules/tone/build/Tone.js', ssr: false }],
}

however that results in this error: [nuxt] Error while initializing app TypeError: Cannot read property 'isUndef' of undefined. Looking at Tone's source I'm pretty sure this is because I'm getting it because the code is still being executed on the server side.

I've seen solutions putting the js file into the static folder and checking process.browser but both result in Tone being undefined.

My question seems to be the same as this one if it's helpful additional context


回答1:


Instead of import a plugin, in your page.vue you can init Tone.js in the mounted() method, because this function is run only from client-side.

Example of page/test.vue file:

<template>
  <div>
    Tone.js
  </div>
</template>

<script>
  export default {
    mounted() {
      var Tone = require("Tone");
      var synth = new Tone.Synth().toMaster();
      synth.triggerAttackRelease("C4", "8n");
    }
  }
</script>


来源:https://stackoverflow.com/questions/45890018/how-to-load-a-resource-on-the-client-side-only-in-nuxt-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!