0

ファイルをエクスポートして、node.jsの他の場所に含める方法を理解するのに苦労しています。

ゲームに取り組んでいて、オブジェクトを定義する変数、または複数の変数、たとえばvarの敵が必要だとします。

var enemy = {
  health: 100,
  strengh: 87
};

そしてそれをvars.jsファイルに保存します。

プロジェクト内の必要な場所からこれらの変数をインポートするにはどうすればよいですか?

前もって感謝します。

4

3 に答える 3

0

それらをエクスポートする必要があります。

だからEnemy.js

var enemy = {
  health: 100,
  strengh: 87
};

exports.health = enemy.health;
exports.strength = enemy.strength;

そしてでotherjsfile.js

var Enemy = require('Enemy.js');


//and then you can do 

console.log(Enemy.health); ///etc

サイドポイント:

'enemy'情報が定期的に変更されており、最新の値を取得したい場合は、次のようにします。

  Object.defineProperty(exports, "health", {
    get: function() {
      return enemy.health;
    }
  }); //instead of `exports.health = enemy.health;`

  Object.defineProperty(exports, "strengh", {
    get: function() {
      return enemy.strengh;
    }
  }); //instead of `exports.strength = enemy.strength;`
于 2012-12-07T14:54:12.350 に答える
0

あなたはvars.jsからエクスポートすることができます

module.exports = {
  health: 100,
  strengh: 87
};

また

var enemy = {
  health: 100,
  strengh: 87
};

module.exports = enemy;

そしてrequireを使用してインポートします:

var enemy = require('./path/to/vars');
于 2012-12-07T14:55:28.717 に答える
0

file.js内:

module.exports = {
  health: 100,
  strengh: 87
}

他のファイル:

var enemy = require('./file'); // (or whatever the relative path to your file is

詳細はこちら。

于 2012-12-07T14:56:30.280 に答える