0
0

More than 1 year has passed since last update.

[JavaScript]moduleのexportとimport

Posted at

これなに?

JavaScriptにおける named exportとdefault exportの違い
Reactでの利用例

moduleを使う時に都度調べていたのですが、全然覚えないのでメモ

default export

1ファイルから1つだけexportする時
defaultという名前でexportされる

// アロー関数の場合のdefault export
const hoge = () => {
  // 処理
}

export default hoge;
// 名前付き関数の場合のdefault export
// つまり関数宣言のdefault export
export default function hoge() {
  // 処理
}

named export

1つのファイルから複数のmoduleをexportする時に使用

export const tee = () => {
 // 処理
}

export const baru = () => {
 // 処理
}
import {hoge, tee} from 'path'

reactでよく使われるやつ

基本的にdefault exportが使われる

reactでnamed exportが使われる例

helper.js
// エントリーポイントでよく使われる
// 全てのexportしたコンポーネントを集めて
// ここから名前付きで再度exportする
{export default as Article} from './Article'
{export default as Content} from './Content'
// メリットは親component側でimport文が
// 1行になること
import {Article, Content} from './helper.js'
0
0
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
0
0