Can Typescript import CommonJS Modules?

Federico picture Federico · Apr 9, 2016 · Viewed 9.7k times · Source

I had this file:

//foo.js
var foo = function () {
    return "foo";
}; 

module.exports = foo;

So, I wanted to import it to my Typescript file. I tried this

//typescript.ts
import * as foo from ("./foo");

Didn't work. I read about this 'ambient' modules, so I added this

//typescript.ts
/// <reference path="./foo.d.ts" />
import * as foo from ("./foo");

And I added a "foo.d.ts" file in the same folder, which had the purpose of letting typescript know about the types of my imported function:

declare module "foo" 
{
    function foo(): string
    export = foo;
}

No luck.

I thought that the problem was with the import syntax (you cannot have the same syntax for es6 and commonjs modules, right?). So I did this.

import foo = require("./foo");

As you might guess, that didn't work either.

I have been able to import d3 an use it successfully when I installed it as a node module with npm install d3 and referenced its d.ts file. I did it with this code:

import * as d3 from "d3";

I haven't been able to do the same with any other module (jquery, box2d, box2d-commonjs, among others), nor with my own libraries as demonstrated above. I am new to Typescript, so probably I'm missing something very obvious, but I haven't been able to figure it out by myself.

Answer

Federico picture Federico · Apr 9, 2016

Turns out it was something really obvious: you had to use the --allowJs option. This worked for me:

tsc --moduleResolution "node" --module "commonjs"  --allowJs main.ts

Though, I still can't figure out why d3 worked while the others libraries didn't.