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

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

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.

回答1:

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 React community has spearheaded and it's a much simpler workflow. Just use CommonJS + webpack (to get lazy require.ensure from here). ?

There's also a quickstart for TypeScript in the browser environment.



回答2:

In the end what I needed was the ability to require() JS content that is compiled on the fly by the server -- which doesn't seem to work with web-pack.

To suppress the errors from the typescript compiler in the original question, I commented out this line from require.d.ts (the RequireJS declaration file):

declare var require: Require; 

and I used the {foo:bar}['f'+'oo'] trick to get tsc to 'forget' the type of the ambient require variable when assigning it to the typed requirejs variable, like so:

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); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!