編集
ES6 でのエクスポートは少し便利です
export const hello = function(){
console.log('hello');
};
インポートは次のようになります
import {hello} from './file';
元の答え
使いたくなるmodule.exports
var hello = function(){
console.log('hello');
};
module.exports = hello;
1 つのことだけをエクスポートする場合は、通常、すべてを 1 行で行います。
var hello = module.exports = function() {
console.log('hello');
};
エクストラ
名前付き関数を使用すると、コードでエラーが発生した場合に、スタック トレースが見栄えがよくなります。これが私がそれを書く方法です
// use a named function ↓
var hello = module.exports = function hello() {
console.log("hello");
};
anonymous
スタック トレースで関数名を表示する代わりに、が表示されますhello
。これにより、バグを非常に簡単に見つけることができます。
コードを簡単にデバッグできるように、このパターンをあらゆる場所で使用しています。ここに別の例があります
// event listeners ↓
mystream.on("end", function onEnd() {
console.log("mystream ended");
};
// callbacks ↓
Pokemon.where({name: "Metapod"}, function pokemonWhere(err, result) {
// do stuff
});
複数のものをエクスポートするexports
場合は、直接使用できますが、key
// lib/foobar.js
exports.foo = function foo() {
console.log("hello foo!");
};
exports.bar = function bar() {
console.log("hello bar!");
};
今、そのファイルを使用するとき
var foobar = require("./lib/foobar");
foobar.foo(); // hello foo!
foobar.bar(); // hello bar!
最後のおまけとして、単一のオブジェクトfoobar.js
をエクスポートしても同じ動作が得られるように書き換える方法を紹介します。
// lib/foobar.js
module.exports = {
foo: function foo() {
console.log("hello foo!");
},
bar: function bar() {
console.log("hello bar!");
}
};
// works the same as before!
これにより、特定のモジュールに最適な方法でモジュールを作成できます。わーい!