无法在同一个TypeScript项目中使用requireJS和Node的Require

我有一个针对Node和浏览器的打字稿项目。 我在某些脚本中使用了Node的require() ,并且在其他脚本中require() 。 我的项目目录如下所示:

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

其中a.ts包含:

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

b.ts包含:

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

其中require.d.tsnode.d.ts从DefinitlyTyped获得。

当我编译我的项目,我得到这些错误:

 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'. 

我使用这个成语来确定加载哪个模块,所以我没有在浏览器中加载节点模块,反之亦然。

 if(typeof module !== 'undefined' && module.exports){ // We're in a Node process }else{ // We're in an AMD module in the browser: } 

有没有办法在同一个项目中使用这两个.d.ts文件。 看来在单独的模块中使用它们是不够的。

有没有办法在同一个项目中使用这两个.d.ts文件

我强烈build议commonjs使用commonjs 。 这就是React社区所带头的,这是一个更简单的工作stream程。 只需使用CommonJS + webpack(从这里获得懒惰require.ensure )。 🌹

在浏览器环境中还有一个TypeScript快速入门。

最后,我需要的是能够require() JS内容,由服务器dynamic编译 – 这似乎不适用于Web包 。

为了在原始问题中抑制打字稿编译器的错误,我从require.d.ts (RequireJS声明文件)中注释掉了这一行:

 declare var require: Require; 

我使用{foo:bar}['f'+'oo']技巧让tsc在将其分配给types化的requirejsvariables时将' requirevariables的types'忘记',如下所示:

 var requirejs:Require; // requirejs if(typeof module !== 'undefined' && module.exports){ // We're in a Node process requirejs = require('requirejs'); }else{ // We're in an AMD module in the browser: requirejs = {require:require}['req'+'ire']; } // use requirejs for dynamic require statements requirejs(gather_requirements(),do_things);