Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Typescript import CommonJS Modules?

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.

like image 566
Federico Avatar asked Apr 09 '16 00:04

Federico


People also ask

Can you use CommonJS in TypeScript?

Yes, you can use it in a same manner that you would use it in Javascript.

Can you use import in CommonJS?

CommonJS modules cannot import ES Modules. You are not able to import . mjs files from . js files.

How do I import a custom module in TypeScript?

Approach: Before importing any module we need to export it from another file. We can create a module by using the export keyword and can use it in other modules by using the import keyword. We can export both class-based modules and function-based modules. as shown below.

Do browsers support CommonJS modules?

CommonJS is a set of standards used to implement modules on JavaScript. The project was started by Mozilla engineer Kevin Dangoor in 2009. CommonJS is mainly used in server-side JS apps with Node, as browsers don't support the use of CommonJS.


1 Answers

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.

like image 171
Federico Avatar answered Oct 14 '22 14:10

Federico