Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import typescript file in javascript file

I am trying to import a typescript file (src/index.ts) in a javascript file(tests/steps/utils.js)

But when I use const index_1 = require("../../src/index"); in my javascript file, it gives an error: Cannot find module '../../src/index'

But the file is right there. Is there any other way to import a typescript file into a javascript file?

like image 826
Salman Arefin Avatar asked Feb 11 '26 04:02

Salman Arefin


2 Answers

You can't. You need to compile the typescript files into js first. However, you can import the built typescript file i.e. js file from its build directory.

like image 184
Ashok Thapa Avatar answered Feb 13 '26 19:02

Ashok Thapa


Updated May 2023: Just found this library: ts-import, it seems can import TS into JS project already.


You can't import a ts into js file.

If you really need the module in .ts file, try to import from dist folder, where the ts compiler output path, or refactor into javascript.

like image 30
Wilson Liao Avatar answered Feb 13 '26 17:02

Wilson Liao