Is it possible for Typescript to utilize Webpack's UMD feature for importing

Is there a method in TypeScript to import a module wrapped by webpack UMD (Universal Module Definition)? For instance:

npm install knockback

The file .js (

node_modules/knockback/knockback.js
) starts like this:

(function webpackUniversalModuleDefinition(root, factory) {
    if(typeof exports === 'object' && typeof module === 'object')
        module.exports = factory(require("knockout"), require("backbone"), ....
    else if(typeof define === 'function' && define.amd)
        define(["knockout", "backbone", "underscore"], function webpackLoadOptionalExternalModuleAmd( ....
        });
    else if(typeof exports === 'object')
        exports["kb"] = factory(require("knockout"), require("backbone"), require("underscore"), (function ....
    else
        root["kb"] = factory(root["ko"], root["Backbone"], root["_"], root["jQuery"]);

When attempting to import this into a .ts file, tsc gives an error:

import * as k from 'knockback/knockback';

TS2307: Build: Cannot find module 'knockback/knockback'.

Are there any alternatives besides modifying the knockback.js file to make tsc recognize and import this .js? My Typescript version is 1.8.

Answer №1

Whenever I attempt to import this into a .ts file, tsc throws an error:

A simple solution is to utilize a type definition file

such as knockback.d.ts

declare module 'knockback/knockback' {
    var bar: any;
    export = bar;
}

Answer №2

Just a heads up, for those who find themselves here attempting to utilize knockback.js with Typescript, there is an existing knockback.d.ts file accessible from DefinitelyTyped. However, the current .d.ts file does not have an export, making it incompatible with external modules. Following the advice from basarat's response, I made adjustments to the .d.ts file as outlined below:

1) Add the following to the end:

declare module "knockback" {
    export = Knockback;
}

2) Eliminate declare var kb: Knockback.Static at the end.

3) Remove the interface Static extends Utils { wrapper and relocate all contents within the Static interface to namespace scope. For example:

Old:

interface Static extends Utils {
    ViewModel;
    CollectionObservable;
    collectionObservable(model?: Backbone.Collection<Backbone.Model>, options?: CollectionOptions): CollectionObservable;
    observable(
        /** the model to observe (can be null) */
        model: Backbone.Model,
        /** the create options. String is a single attribute name, Array is an array of attribute names. */
        options: IObservableOptions,
        /** the viewModel */
        vm?: ViewModel): KnockoutObservable<any>;
    ...
}

New:

function collectionObservable(model?: Backbone.Collection<Backbone.Model>, options?: CollectionOptions): CollectionObservable;
function observable(
    /** the model to observe (can be null) */
    model: Backbone.Model,
    /** the create options. String is a single attribute name, Array is an array of attribute names. */
    options: IObservableOptions,
    /** the viewModel */
    vm?: ViewModel): KnockoutObservable<any>;
...

With these modifications, usage will resemble the following:

import * as kb from 'knockback';

class MyViewModel extends kb.ViewModel {
    public name: KnockoutObservable<string>;

    constructor(model: Backbone.Model) {
        super();

        this.name = kb.observable(model, "name");
    }
}

var model = new Backbone.Model({ name: "Hello World" });
var viewModel = new MyViewModel(model);

kb.applyBindings(viewModel, $("#kb_observable")[0]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The test function is not recognized by Cordova when the device is ready

Within my app.component.ts file, I have the following code snippet: export class AppComponent implements OnInit { constructor(private auth: AuthService, private fireBaseService: FirebaseService, ) {} ngOnInit() { this.auth.run(); document.addE ...

What is the subclass of all object literal types in TypeScript?

With the `strictFunctionTypes` setting turned on, function parameters are checked contravariantly. interface Func<T> { (p: T): unknown } declare let b: Func<{p1: string}> declare let c: Func<{p2: number}> declare let d: Func<{p3: nu ...

Error: Unable to locate metadata for the entity "BusinessApplication"

I have been utilizing TypeORM smoothly for some time, but out of the blue, I encountered this error during an API call: EntityMetadataNotFound: No metadata for "BusinessApplication" was found. at new EntityMetadataNotFoundError (C:\Users\Rob ...

Is there a way to ensure my react app remains operational despite the presence of lint errors?

As I delve into a React project utilizing webpack, the 'npm start' command tends to drag on during the build process. However, if lint errors are detected, it abruptly fails at the end with an 'Exit status 1', forcing me to rectify the ...

Storing redux dispatch action using the useRef hook in Typescript

Currently, I am attempting to store the redux action dispatch in a React reference using useRef. My goal is to be able to utilize it for aborting actions when a specific button is clicked. Unfortunately, I am facing challenges with assigning the correct ty ...

Refreshing Angular 9 component elements when data is updated

Currently, I am working with Angular 9 and facing an issue where the data of a menu item does not dynamically change when a user logs in. The problem arises because the menu loads along with the home page initially, causing the changes in data to not be re ...

Attempting to create a TypeScript + React component that can accept multiple types of props, but running into the issue where only the common prop is accessible

I am looking to create a component named Foo that can accept two different sets of props: Foo({a: 'a'}) Foo({a: 'a', b: 'b', c:'c'}) The prop {a: 'a'} is mandatory. These scenarios should be considered i ...

Having trouble converting the JSON object received from the server into the necessary type to analyze the data

I am new to angular and struggling with converting a JSON object from the server into a custom datatype to render in HTML using ngFor. Any help would be appreciated as I have tried multiple approaches without success. Apologies for the simple HTML page, I ...

What is the process for using infer to determine the return type of a void function?

I am trying to gain a better understanding of how to utilize the infer keyword in TypeScript. Is this an appropriate example demonstrating the correct usage of infer? I simply want to infer the return type of the function below: const [name, setName] = u ...

Angular 4 and the process of HTML encoding

Looking for assistance with html encoding in angular 4. I have product records stored in a database, with the fullDescription field in this particular format: &lt;div align="justify"&gt;&lt;span&gt; When using <div *ngIf="product" [inn ...

Handling HTTP errors in Angular when receiving a JSON response

I'm struggling to resolve this issue and I've searched online with no luck. The problem lies in my post call implementation, which looks like this: return this.http.post(url, body, { headers: ConnectFunctions.getHeader() }).pipe( map(result =&g ...

What is the best way to incorporate a TypeScript function within a JQuery function?

I'm facing an issue with installing the Angular Instascan library, so I am using it without installing and only importing the script. In order to make it work, I have to use JQuery in my TypeScript file within the component. Is there a way to call a T ...

Can you explain the purpose of this TypeScript code snippet? It declares a variable testOptions that can only be assigned one of the values "Undecided," "Yes," or "No," with a default value of "Undecided."

const testOptions: "Undecided" | "Yes" | "No" = "Undecided"; Can you explain the significance of this code snippet in typescript? How would you classify the variable testOptions? Is testOptions considered an array, string, or another d ...

What is the reason for the lack of overlap between types in an enum?

I'm having trouble understanding why TypeScript is indicating that my condition will always be false. This is because there is no type overlap between Action.UP | Action.DOWN and Action.LEFT in this specific scenario. You can view the code snippet and ...

Utilizing data from the home component in another component: A guide

Here is the code I am working with, showcasing how to utilize (this.categoryType) in another component: getCategoryDetails(){ return this.http.get('ip/ramu/api/api/…') .map((res:Response) => res.json()); } The above code snippet is utilize ...

A guide to implementing unit tests for Angular directives with the Jest testing framework

I am currently integrating jest for unit testing in my Angular project and I am relatively new to using jest for unit tests. Below is the code snippet for DragDropDirective: @HostListener('dragenter',['$event']) @HostListener(& ...

Exporting a constant as a default in TypeScript

We are currently developing a TypeScript library that will be published to our private NPM environment. The goal is for this library to be usable in TS, ES6, or ES5 projects. Let's call the npm package foo. The main file of the library serves as an e ...

The name 'console' could not be located

I am currently working with Angular2-Meteor and TypeScript within the Meteor framework version 1.3.2.4. When I utilize console.log('test'); on the server side, it functions as expected. However, I encountered a warning in my terminal: Cannot ...

Fix the TypeScript issue encountered during a CDK upgrade process

After upgrading to version 2.0 of CDK and running npm install, I encountered an issue with the code line Name: 'application-name'. const nonplclAppNames = configs['nonplclAppNames'].split(','); let nonplclAppNamesMatchingState ...

When the button is clicked, a fresh row will be added to the table and filled with data

In my table, I display the Article Number and Description of werbedata. After populating all the data in the table, I want to add a new article and description. When I click on 'add', that row should remain unchanged with blank fields added below ...