Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Typescript import Webpack UMD?

Using TypeScript, is there some way to import a module that has been wrapped by webpack UMD (Universal Module Definition)? For example:

npm install knockback

The .js file (node_modules/knockback/knockback.js) begins 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 I try to import this into a .ts file, tsc produces an error:

import * as k from 'knockback/knockback';

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

Is there anything I can do, short of editing the knockback.js file, to convince tsc to import this .js? I'm using Typescript 1.8.

like image 998
cbranch Avatar asked Sep 25 '22 05:09

cbranch


1 Answers

When I try to import this into a .ts file, tsc produces an error:

You can use a type definition file quite easily

file knockback.d.ts

declare module 'knockback/knockback' {
    var foo: any;
    export = foo;
}
like image 90
basarat Avatar answered Oct 12 '22 10:10

basarat