简体   繁体   中英

Can I create definition file for local JavaScript module?

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 compilation of this import succeeds?

What is needed for this to work is typescript definition file named same as JavaScript file ( adts 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 adts 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 compiler will not complain. Also your IDE will not shown the errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM