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

标签 node.js typescript requirejs

我有一个针对 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.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'.

我使用这个习惯用法来确定要加载哪些模块,因此我不会在浏览器中加载 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/

相关文章:

javascript - JS如何用单行设置范围之外的值

reactjs - 在 React TypeScript 中使用异步等待和 try 和 catch 子句处理 HTTP 错误

typescript - 在 Typescript 中导出常量并将其导入另一个模块

javascript - Backbone.js 使用集合渲染 View

node.js - 如何使用计算字段在 Waterline 中进行排序

node.js - 循环中的 Node JS Api 请求

javascript - RequireJS 配置不支持 AMD 的模块

javascript - JS — 尝试返回 AJAX 数据

node.js - 实时应用对 pod 代码源的更改 - npm

javascript - 需要简单的 Express.js XML 服务器示例