export defaultとimport
7781 ワード
基本的に共通の判定用関数、固定値などは固有ファイルではなく共通化していきたいので
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側
切り出した設定・ロジック
const HAT = 'M'
const HIGE = 1
const isM = (hat) => hat === HAT
const isHige = (player) => player === HIGE
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側
import { HAT, isHige } from '/path/to/game'
// HAT = 'M'
// isHige = function()
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側
import game from '/path/to/game'
import { HAT, isHige } from '/path/to/game'
デフォルトエクスポートも名前付きエクスポートもどちらも書く
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回記述が必要なので、ロジックは別途定義しておいて変数だけ指定する形が良さそう。
参考
Author And Source
この問題について(export defaultとimport), 我々は、より多くの情報をここで見つけました https://qiita.com/yama-t/items/7aff15347e86813ed603著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .