简体   繁体   中英

How to import local JavaScript file into NodeJS TypeScript project?

Existing project in NodeJS and I'm writing single new part of project in TypeScript (in this case my CLI).

My folder looks something like this:

|_ cli.ts << New file that describes new functionality
|_ old-lib.js << Existing large library

In cli.ts I've no idea how to include the old-lib.js . I'm familiar with using ambient *.d.ts files when importing a Node module (that would reside in node_modules ). The problem occurs when I'm trying to include a local JavaScript file.

Approach 1

The first approach satisfies the TypeScript compiler but upsets Node:

/// <reference path="modules.d.ts" />
import oldLib = require('old-lib');

NodeJS looks for a package in node_modules due to the lack of ./ at the beginning of the module name.

Error: Cannot find module 'old-lib'

Approach 2

Use the NodeJS require syntax. This fails to match an entry in the modules.d.ts file: import oldLib = require('./old-lib');

... error TS2307: Cannot find module './old-lib'.

There must be an approach for incrementally including legacy JavaScript files without renaming them to TS files and resolving the errors (ie by just describing the interface in the same way as one would do for node modules).

Let me know if I need to add more details, thanks.

error TS2307: Cannot find module './old-lib'.

Reorganize your project so that you have :

|_ cli.ts << New file that describes new functionality
|_ old-lib.js << Existing large library
|_ old-lib.d.ts << Existing large library

And put stuff like the following into this new old-lib.d.ts file:

export var foo:number; 
export var bar:string;

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