2016-06-24 7 views
1

ノードとブラウザの両方を対象とするタイスクリプトプロジェクトがあります。いくつかのスクリプトではNodeのrequire()を使用していますが、他の場合はJSTのrequire()が必要です。同じTypeScriptプロジェクトでrequireJSとNodeの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.tsDefinitlyTypedから得られる私のプロジェクトディレクトリは次のようになります。私は私のプロジェクトをコンパイルすると

、私はこれらのエラーを取得:

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のファイルの両方を使用する方法はあります。それは別のモジュールでそれらを使用するのは不十分だと思われます。

答えて

3

私は非常にどこでもcommonjs一緒に行くお勧めします、同じプロジェクトに

をこれら.d.tsファイルの両方を使用する方法はあります。それがReactコミュニティが先導してきたものであり、はるかに簡単なワークフローです。 CommonJS + webpack(怠惰なrequire.ensurehereから取得する)を使用してください。

TypeScript in the browser environmentのクイックスタートもあります。

+0

ありがとう! – Jthorpe

+0

心配はいりません。 Fwiw私はhttps://github.com/alm-tools/almを開発するために使用するこのワークフローを持っています。新しい技術を試してみるのは簡単です。しかし、私は怠惰な 'require.ensure'の必要はありません:) – basarat

0

私が必要としていたのは、require()サーバーでフライでコンパイルされたJSコンテンツです。which doesn't seem to work with web-pack

declare var require: Require; 

と私はtsc忘れ」にを取得するために{foo:bar}['f'+'oo']トリックを使用:元の質問でtypescriptですコンパイラからエラーを抑制するために

は、私がrequire.d.ts(RequireJS宣言ファイル)からこの行をコメントアウト周囲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); 
関連する問題