【问题标题】:Unable to use requireJS and Node's Require in the same TypeScript project无法在同一个 TypeScript 项目中使用 requireJS 和 Node 的 Require
【发布时间】:2016-10-27 06:34:12
【问题描述】:

我有一个针对 Node 和浏览器的打字稿项目。我在一些脚本中使用 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'.

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

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

    // We're in a Node process

}else{

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

}

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

【问题讨论】:

    标签: node.js typescript requirejs


    【解决方案1】:

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

    我强烈建议到处使用commonjs。这就是 React 社区带头的东西,它是一个更简单的工作流程。只需使用 CommonJS + webpack(从here 变得懒惰require.ensure)。 ?

    还有TypeScript in the browser environment 的快速入门。

    【讨论】:

    • 不用担心。 Fwiw 我有这个工作流程我用来开发github.com/alm-tools/alm 超级容易试验新技术。但是我不需要懒惰的require.ensure :)
    【解决方案2】:

    最后我需要的是能够require() 由服务器即时编译的JS 内容——which doesn't seem to work with web-pack

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

    declare var require: Require;
    

    我使用{foo:bar}['f'+'oo'] 技巧让tsc 在将环境require 变量分配给类型化的requirejs 变量时“忘记”它的类型,如下所示:

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

    【讨论】:

      猜你喜欢
      • 2017-06-13
      • 1970-01-01
      • 2017-10-23
      • 2015-03-21
      • 2016-06-27
      • 2014-04-16
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多