Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

javascript - How to import a js library without definition file in typescript file

I want to switch from JavaScript to TypeScript to help with code management as our project gets larger. We utilize, however, lots of libraries as amd Modules, which we do not want to convert to TypeScript.

We still want to import them into TypeScript files, but we also do not want to generate definition files. How can we achieve that?

e.g. The new Typescript file:

/// <reference path="../../../../definetelyTyped/jquery.d.ts" />
/// <reference path="../../../../definetelyTyped/require.d.ts" />
import $ = require('jquery');
import alert = require('lib/errorInfoHandler');

Here, lib/errorInfoHandler is an amd module included in a huge JavaScript library that we do not want to touch.

Using the above code produces the following errors:

Unable to resolve external module ''lib/errorInfoHandler'' 
Module cannot be aliased to a non-module type.

This should actually produce the following code:

define(["require", "exports", "jquery", "lib/errorInfoHandler"], function(require, exports, $, alert) {
...

}

Is there a way to import a JavaScript library into TypeScript as an amd Module and use it inside the TypeScript file without making a definition file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A combination of the 2 answers given here worked for me.

//errorInfoHandler.d.ts
declare module "lib/errorInfoHandler" {
   var noTypeInfoYet: any; // any var name here really
   export = noTypeInfoYet;
}

I'm still new to TypeScript but it looks as if this is just a way to tell TypeScript to leave off by exporting a dummy variable with no type information on it.

EDIT

It has been noted in the comments for this answer that you can achieve the same result by simply declaring:

//errorInfoHandler.d.ts
declare module "*";

See the github comment here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...