I have a standard web page (not an app rendered with angular, react, vue, etc) that uses jQuery, and other libraries.
I want to integrate good practices with TypeScript. What is the best way to do this?
My current idea is to have 3 files:
- the index.d.ts (describes the types of my module)
- the test.ts (the implementation of the types described in the index.d.ts)
- the page.js (the file that uses the javascript defined in the test.js -- output from the test.ts)
I currently have these contents:
index.d.ts
// Type definitions for test 1.0.0
// Project: Test
// Definitions by: Author Name
/// <reference path="../../lib/@types/jquery/index.d.ts" />
declare namespace TestNS {
export class TestClass {
// Fields
element: JQuery;
value: string;
constructor(element: JQuery, val: string);
OnCreate();
static AttachToJQuery(jq: JQueryStatic): void;
}
interface JQuery {
TestClass(element: JQuery, val?: string): TestNS.TestClass;
}
interface JQueryStatic {
TestClass(element: JQuery, val?: string): TestNS.TestClass;
}
}
Test.ts (loaded 2nd, after jQuery)
/// <reference path="../../lib/@types/jquery/index.d.ts" />
/// <reference path="./index.d.ts" />
export namespace TestNS {
export class TestClass {
// Fields
element: JQuery;
value: string;
constructor(element: JQuery, val: string) {
this.element = element;
this.value = val;
this.OnCreate();
}
OnCreate() {
this.element.data('test-value', this.value);
}
static AttachToJQuery(jq: JQueryStatic) {
//no jQuery around
if (!jq) {
return false;
}
jq.fn.extend({
TestNS: function(newVal) {
return this.each(function() {
var obj = jq(this);
new TestNS.TestClass(obj, newVal);
});
}
});
}//attach to jquery method (to easily work with noconflict mode)
}//test class
}
page.js (loaded last)
let newJquery:JQueryStatic = jQuery.noConflict();
TestNS.TestClass.AttachToJQuery(newJquery);
let testElems = newJquery(".testClass");
testElems.TestClass();
My goal is to have my code neatly organized into a namespace in typescript, as well as on the page (but doing so in typescript gives errors related to duplicate identifiers) as well as being modular and extensible. I understand that I should publish my types under the "node_modules/@types" directory, but I simply want them all encapsulated in this module for now.
I have tried using a module, and importing what is defined in the index.d.ts, but TypeScript says I cannot import this file, and that the module name cannot be found. I did learn that if I use a module, it should be accompanied with a loader, such as CommonJS, RequireJS or AMD, but I would prefer to avoid that for now (if it's not a horrible practice to do so, as I want to minimize the levels of complexity for now).
I've tried looking at other projects, but they all use a loader, which seems a bit overkill for this kind of script.
Is there a good way to go about this?