Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS How to import JS file into TypeScript

I'm new with TypeScript. I'm currently learning NodeJS Loopback 4 framework which use Typescript language. And my question is how to import some function, class which has been exported in JS file into my TS file. After search several way but it still doesn't work with me. Here's example:

  // /src/index.ts
    import {plus} from './lib/test';

    console.log(plus(1,2));

// /src/lib/test.js
    export function plus(x, y) {
      return x + y;
    }

I also try using definition typescript like this

// /src/lib/test.d.ts
export declare function plus(x: number, y: number): number;

But still got error when import this function in index.ts file

Error: Cannot find module './lib/test' at Function.Module._resolveFilename (module.js:543:15)

like image 591
Quoc Van Tang Avatar asked Jan 23 '19 06:01

Quoc Van Tang


1 Answers

It looks like the tsconfig.json doesn't have 'allowJs' enabled because it exports declarations.

Is there a reason you are not wanting this to be a typescript file? If you change test.js to test.ts, by making it a .ts should allow it to be recognised in your index file.

UPDATE

Full chat history to get to this point can be found here. Repository used to test found here

OK so easy solution as @maaz-syed-adeeb mentions will work:

import { path } from './lib/test.js'

The reason the extension is important is because the definition file takes priority over a javascript file in a typescript environment. That is why the module import was blowing up.

To avoid specifying the .js extension you can also setup your directory structure like this:

src
|- index.ts
|- lib
  |- test.js
  |- test.d.ts
  |- index.[js|ts]

in ./lib/index file export all from test:

//./src/lib/index.[js|ts]
export * from './test'

and then import all from lib:

// ./src/index.ts
import { path } from './lib'
// or
import { path } from './lib/test.js'

If you are using a blend of javascript and typescript (say you are moving over to typescript with an existing code base), you will need to update your tsconfig.json to include so you don't get the warnings in your IDE:

{
  "compilerOptions": {
    "allowJs": true,
    "declaration": false
  }
}

This is so your javascript files will be transpiled to your destination directory along with the typescript files.

like image 70
Christopher Slater Avatar answered Oct 20 '22 13:10

Christopher Slater