Search code examples
javascriptjquerytypescripttsc

How to compile TypeScript to JavaScript with jQuery, without any additional libraries or frameworks (NPM, etc.)


I have an extremely simple single-page dashboard that does things like grab the weather, the subway alerts, etc. and I refresh it locally on my machine. It looked like:

project/
  index.html
  jquery-3.3.1.min.js
  script.js

And I wanted to convert it to TypeScript. I ported script.js to TypeScript, but in order to use jQuery had to download the definition file from here. I now have:

project/
  index.html
  jquery.d.ts
  script.ts

The first two lines of my TypeScript file are:

/// <reference path ="./jquery.d.ts"/>
import * as $ from "jquery"

When I run tsc *.ts, it compiles my script successfully, but the first four lines of the resulting/compiled JavaScript file are:

"use strict";
exports.__esModule = true;
/// <reference path ="./jquery.d.ts"/>
var $ = require("jquery");

And this fails in my browser with:

exports.__esModule = true; // Can't find variable: exports

I'm a pretty weak front-end developer beyond HTML/JS/jQuery, so I'm not sure where to start - I did some Googling but not much came up.


Solution

  • If you mean so...

    use declare var $: JQuery if the type is defined

    else use declare vas $: any

    for the case that your editor (f.e. VSCode) supports script var declarations use

    { 
     name: "$",
     type: JQuery (or any),
     ofReference: {
      scriptSrc: ["*jquery.js", "*jquery.min.js", "*code.jquery*"] 
     }
    }