Search code examples
javascripttypescriptvue.jsyoutube-iframe-apitsc

Typescript giving me errors with variables, and is also compiling code that javascript does not know about


I am using typescript, and i can't run my code. something that would be extremely easy to make with javascript, has me running around so many circles.

I am using the youtube API, and referencing via a script tag. the code works just fine is javascript, but typescript will not let me compile the code because it says that there is an undefined variable. index.html

    <script src="/liveRoom/src/framework/vue.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://www.youtube.com/iframe_api"></script>
    <script src="/liveRoom/src/app.js"></script>

app.js

import Vue from 'vue';
const socket : any = io();

function onYoutubeIFrameAPIReady() : void {
    let player : object = new YT.Player('player', { //YT is undefined apparently
        width: '640',
        height: '390',
        videoID: 'null',
        events: {
            'onStateChange': onPlayerStateChange
        }

    });
}
function onPlayerStateChange() {

}

socket.on('videoID', function (videoID : string) : void {
    console.log('the id is: ' + videoID);
    var app = new Vue({
        el: '#vID',
        data: {
            vID: videoID
        }
    });

});
console.log('asas');

And if this isn't chaotic enough, even if i remove this youtube API, and try to create my own system, it wont even let me use vue because when i import it, it send this to my JS file:


exports.__esModule = true;
var vue_1 = require("vue");

I have never heard of exports. in javascript, and apparently neither has javascript! which is why i am getting this error even if i decide to only use vue:

Uncaught ReferenceError: exports is not defined
    at app.js:2

Typescript is suppose to save me time, but at this point i would probably be finishing up with my project instead of just starting it.


Solution

  • The problem that you're having is that typescript does not have access to the types for vue. This is because you're importing it with a script tag (??) which is not the typical way for web development.

    You should most likely set yourself up with Webpack and the like, or, if you don't want to spend time working out how to configure that, use a zero-config tool like Vue CLI.

    If you don't want to do that, you can try using npm install vue inside of the directory of your typescript project, but make sure that it's the same version of vue that you are importing via your script tag. Good luck!