typescript - Can I create definition file for local JavaScript module? - Stack Overflow

Let's say I have a a.js file that contains:export function a() {}and I want it to import it from t

Let's say I have a a.js file that contains:

export function a() {}

and I want it to import it from the file b.ts (in the same directory) like that:

import { a } from './a.js'

How can I tell TypeScript what the file a.js contains so that pilation of this import succeeds?

Let's say I have a a.js file that contains:

export function a() {}

and I want it to import it from the file b.ts (in the same directory) like that:

import { a } from './a.js'

How can I tell TypeScript what the file a.js contains so that pilation of this import succeeds?

Share Improve this question asked Sep 15, 2016 at 14:05 Kamil SzotKamil Szot 17.8k8 gold badges64 silver badges66 bronze badges 3
  • What error are you getting ? – blorkfish Commented Sep 15, 2016 at 15:04
  • @blorkfish b.ts(1,15): error TS2307: Cannot find module './a.js'. – Kamil Szot Commented Sep 15, 2016 at 15:13
  • I think you will need to check the module resolution documentation. typescriptlang/docs/handbook/module-resolution.html – blorkfish Commented Sep 15, 2016 at 15:17
Add a ment  | 

2 Answers 2

Reset to default 6

What is needed for this to work is typescript definition file named same as JavaScript file (a.d.ts in this case) that contains:

export function a();

It can also specify parameter types, additional exported functions and classes and must use export keyword to indicate what the JavaScript file actually exposes.

One other change is that this JavaScript module needs to be then imported in b.ts as:

import { a } from './a' // without .js

so it takes typescript definition file into account. It will still use implementation from a.js file. It works with webpack too.


If you don't want to describe what's inside a.js and have TypeScript just accept it you can create a.d.ts file like that:

declare var whateva:any;
export = whateva;

Then you can import it like this:

import * as ajs from './a'

and then refer to any function exposed by a.js in your TypeScript files like that:

ajs.a();

You can just simply use a statement:

declare var a:any;

(after the import) in this same file you are using the a (i this case in b.ts). Thanks to this the TS piler will not plain. Also your IDE will not shown the errors.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745622102a4636581.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信