我有一个针对 Node 和浏览器的 typescript 项目。我在某些脚本中使用 Node 的 require()
,在其他脚本中使用 requireJS 的 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.ts
和 node.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'.
我使用这个习惯用法来确定要加载哪些模块,因此我不会在浏览器中加载 Node 模块,反之亦然。
if(typeof module !== 'undefined' && module.exports){
// We're in a Node process
}else{
// We're in an AMD module in the browser:
}
有没有办法在同一个项目中使用这两个 .d.ts
文件。看来在单独的模块中使用它们是不够的。
最佳答案
Is there a way to use both of these .d.ts files in the same project
我强烈建议在任何地方都使用 commonjs
。这就是 React 社区所倡导的,并且它的工作流程要简单得多。只需使用 CommonJS + webpack(从 here 获取惰性 require.ensure
)。 🌹
还有 TypeScript in the browser environment 的快速入门.
关于node.js - 无法在同一个 TypeScript 项目中使用 requireJS 和 Node 的 Require,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38016793/