export defaultとimport


基本的に共通の判定用関数、固定値などは固有ファイルではなく共通化していきたいので
export、importを活用中。切り出しているうちにexportの仕様を調べたのでメモ。

JS

切り出した設定・ロジック
const HAT = 'M'
const HIGE = 1
const isM = (hat) => hat === HAT
const isHige = (player) => player === HIGE

まとめてimportしたい場合

import側

import 'game' from '/path/to/game'
// game { HAT: 'M', HIGE: 1, isM: function(), isHige: function() }

export側

export defaultを設定する(デフォルトエクスポート)

const HAT = 'M'
const HIGE = 1
const isM = (hat) => hat === HAT
const isHige = (player) => player === HIGE

export default {
  HAT,
  HIGE,
  isM,
  isHige
}

メソッド等を個別にimportしたい場合

import側

import { HAT, isHige } from '/path/to/game'
// HAT = 'M'
// isHige = function()

export側

defaultをつけずにexport設定を書く(名前付きexport)

const HAT = 'M'
const HIGE = 1
const isM = (hat) => hat === HAT
const isHige = (player) => player === HIGE

export {
  HAT,
  HIGE,
  isM,
  isHige
}

個別・まとめてどちらも使いたい

import側

import game from '/path/to/game'
import { HAT, isHige } from '/path/to/game'

export側

デフォルトエクスポートも名前付きエクスポートもどちらも書く

const HAT = 'M'
const HIGE = 1
const isM = (hat) => hat === HAT
const isHige = (player) => player === HIGE

export {
  HAT,
  HIGE,
  isM,
  isHige
}

export default {
  HAT,
  HIGE,
  isM,
  isHige
}

まとめ

  • 名前付きエクスポートとデフォルトエクスポートでimport時の挙動が異なる。
  • デフォルトエクスポートだけ書いていると名前指定のimportはできない。
  • デフォルトも名前付きも両方使いたい場合、 export部分に具体的なロジックを書くと2回記述が必要なので、ロジックは別途定義しておいて変数だけ指定する形が良さそう。

参考