Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9314

[Node.js]モジュール定義について整理(exports-require / export-import)

$
0
0

はじめに

あるファイルに定義した関数等を別のファイルで使いたいときにどうするか。

Node.jsでは二つのやり方がある。

  1. exportsで公開してrequireで読み込む(CommonJS)
  2. exportで公開してimportで読み込む(ES2015)

常に使えるのは1の方法。Babelを使うなら2の方法でも可能。
どちらを選んでもメリット・デメリットがあるわけではない(と思う)ので、お好きなほうで。

個人的には、常に使える1の方法がいいような気がしている。

使用例

exportsで公開してrequireで読み込む(CommonJS)

一つの関数だけをエクスポート

module.js
// 関数を定義constf=()=>{console.log('Hello!')}// 関数を公開module.exports=f
client.js
constf=require('./module')f()// Hello!

エクスポートするのは関数に限らず、文字列や数値でも良い。

複数の関数をエクスポート

module.js
// 関数を定義constf1=()=>console.log('Hello!')constf2=()=>console.log('World!')// 別名をつけて、二つの関数を公開module.exports={sayHello:f1,sayWorld:f2}
client.js
constmod=require('./module')mod.sayHello()// Hello!mod.sayWorld()// World!

クラスをエクスポート

module.js
// クラスを定義classPerson{constructor(name){this.name=name}greet(params){console.log(`Hello, ${this.name}!`)}}// 公開module.exports=Person
client.js
constPerson=require('./module')p=newPerson('aki')p.greet()// Hello, aki!

おまけ:選択してインポート

module.js
constf1=()=>console.log('Hello!')constf2=()=>console.log('World!')module.exports={sayHello:f1,sayWorld:f2}
client.js
// インポートする対象を選択するconst{sayHello}=require('./module')sayHello()// Hello!

exportで公開してimportで読み込む(ES2015)

下記の参考資料を参照。いつか書く。

参考資料

1. exports - require(CommonJS)

2. export - import((ES2015))


Viewing all articles
Browse latest Browse all 9314

Trending Articles