Jthorpe Jthorpe - 3 months ago 69
Node.js Question

Unable to use requireJS and Node's Require in the same TypeScript project

I have a typescript project targeted at both Node and the browser. I'm using Node's

require()
in some scripts and requireJS's
require()
in others. My project directory looks like this:

myProject
\-- a.ts
\-- b.ts
\-- node.d.ts
\-- require.d.ts


where
a.ts
contains:

/// <reference path="./node.d.ts" />
var cp = require('child-process');
var a = 'hello world'
export = a


and
b.ts
contains:

/// <reference path="./require.d.ts" />
require('hello',function(x){console.log('world')});
var b = 'hello world'
export = b


and where
require.d.ts
and
node.d.ts
are obtained from DefinitlyTyped.

When I compile my project, I get these errors:

b.ts(2,1): error TS2346: Supplied parameters do not match any signature of call target.
require.d.ts(396,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'require' must be of type 'NodeRequire', but here has type 'Require'.


I use this idiom to determine which modules to load, so I'm not loading a node module in the browser or vice versa.

if(typeof module !== 'undefined' && module.exports){

// We're in a Node process

}else{

// We're in an AMD module in the browser:

}


Is there a way to use both of these
.d.ts
files in the same project. It seems using them in separate modules is not enough.

Answer

Is there a way to use both of these .d.ts files in the same project

I highly recommend going with commonjs everywhere. That is what the ReactJS comminity has spearheaded and its a much simpler workflow. Just use CommonJS + Webpack (to get lazy require.ensure from here)

Comments