admin管理员组

文章数量:1434943

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.

本文标签: typescriptCan I create definition file for local JavaScript moduleStack Overflow