LoginSignup
1
3

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-01-23

はじめに

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

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

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

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

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

使用例

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

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

module.js
// 関数を定義
const f = () => {
    console.log('Hello!')
}

// 関数を公開
module.exports = f
client.js
const f = require('./module')
f()  // Hello!

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

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

module.js
// 関数を定義
const f1 = () => console.log('Hello!')
const f2 = () => console.log('World!')

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

クラスをエクスポート

module.js
// クラスを定義
class Person {
    constructor(name) {
        this.name = name
    }

    greet(params) {
        console.log(`Hello, ${this.name}!`)
    }
}

// 公開
module.exports = Person
client.js
const Person = require('./module')
p = new Person('aki')
p.greet() // Hello, aki!

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

module.js
const f1 = () => console.log('Hello!')
const f2 = () => 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))

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3