Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing JS File into Typescript

I'm looking at moving over to Typescript and currently looking at doing this slowly if possible file by file.

Now the system I currently have is built with Webpack and I'm wanting to continue this for building my overall bundle.

I have a .d.ts file for the definition but I need my file to continue importing which currently is throwing an error.

/// <reference path="../../../../vendor/src/foo.d.ts" />
import foo = require('../../../../vendor/src/foo.js');

foo('something');

This currently is throwing errors I have also tried without the reference path and this seems to raise an error that it is not a module. Currently the only way I can have no errors raised is not importing and simply adding the reference but this will mean that webpack will not know the location of my file.

Any ideas I have searched quite a lot but I can't really make sense of importing JS files into Typescript.

like image 333
Nick White Avatar asked Nov 04 '15 14:11

Nick White


People also ask

Can you add JavaScript to TypeScript?

The TypeScript compiler supports a mix of JavaScript and TypeScript files if we use the compiler option --allowJs : TypeScript files are compiled. JavaScript files are simply copied over to the output directory (after a few simple type checks).

How do I import files into TypeScript?

To import a class from another file in TypeScript: Export the class from file A , e.g. export class Employee {} . Import the class in file B as import { Employee } from './another-file' . Use the class in file B .


1 Answers

Any ideas I have searched quite a lot but I can't really make sense of importing JS files into Typescript.

For webpack all you need is to declare the require function and do what you are already used to:

var foo = require('../../../../vendor/src/foo');

The require function type definition is present here : https://github.com/TypeStrong/ts-loader#loading-other-resources-and-code-splitting

If you want to use foo in a stronger manner... recommend porting it over to .ts as well instead of struggling to build and then maintain a .d.ts file for it.

like image 105
basarat Avatar answered Oct 13 '22 15:10

basarat