I created a web radio player using Vue Cli and now I need to incorporate a new feature with an external library, specifically designed for handling audio advertisements. The catch is that this library must be loaded from a remote server and cannot be simply downloaded and imported locally.
Initial Setup
Within my Vue App, I have various components and one of them includes an audio tag responsible for radio playback. My goal is to detect when the play button is clicked, load the advertisement, play it, and then resume regular radio playback.
Approaches I've Tried
- Initially, I attempted loading the external library in the index.html file. While this worked, I discovered that I couldn't interact with the player being loaded in Vue. For instance, trying to listen for the play event in the index.html file (
), resulted in receiving an error stating "audio not defined" in the web console.audio.addEventListener("play", onPlay);
- Subsequently, I tried loading the external library within the mounted() section of my component:
const triton = document.createElement('script')
triton.setAttribute('src', '//sdk.listenlive.co/web/2.9/td-sdk.min.js')
document.head.appendChild(triton)
this.initPlayerSDK()
triton.onload = () => {
let player = new TDSdk(this.tdPlayerConfig)
console.log(player)
}
The issue with this approach arose after running npm run serve
, where I encountered the message 'TDSdk' is not defined
. This makes sense as I am loading the external JS file, but webpack isn't interpreting its content since it's done at runtime. Adding the external library in my vue.config.js didn't resolve this either:
vue.config.js
const path = require('path')
module.exports = {
publicPath: './',
chainWebpack: config => {
config.module
.rule('images')
.test(/\.(png|jpe?g|gif|webp)(\?.*)?$/)
.use('url-loader')
.loader('file-loader') // not url-loader but file-loader !
.tap((options) => { // not .option() but .tap(options...)
// modify the options...
options.name = 'img/[name].[ext]'
return options
}),
config.externals([
{
'tdSdk': 'TDSdk'
},
])
},
css: {
loaderOptions: {
sass: {
sassOptions: {
includePaths: [path.resolve(__dirname, './node_modules/compass-mixins/lib')]
}
}
}
},
externals: {
tdSdk: 'TDSdk'
}
}
myComponent.vue
import tdSdk from 'tdSdk'