问题
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