LoginSignup
35
19

More than 3 years have passed since last update.

React モジュールのimport、exportについて

Posted at

モジュール化について

  • 他言語では昔からある概念
  • JavaScriptではES2015(ES6)から採用
  • 基本的に1ファイル=1モジュール
  • 任意の場所で読み込んで使用できる

モジュール化のメリット

  1. 分割統治できる
    大規模プログラムでも管理しやすくなる
  2. 任意の場所で読み込める
    必要なものを必要な分だけ
  3. 再利用できる
    何度も同じコードを書かなくていい

名前付きexport

1モジュールから複数の関数をexport
クラスはexportできない

index.js
export function Foo() {
  return (
    <h1>FOO</h1>
  );
}
export const Bar = () => {
  return (
    <h1>BAR</h1>
  );
}

名前なし(default)export

  • 1ファイル(1モジュール) 1export
  • ES6で推奨されているexport方法
  • アロー関数は宣言後にexport
  • クラスをexportできる
Foo.js
export default function Foo() {
  return (
    <h1>FOO</h1>
  );
}
Bar.js
const Bar = () => {
  return (
    <h1>BAR</h1>
  );
}
export default Bar;
Hoge.js
export default class Hoge extends Fuga {
  render() {
    return (
      <h1>Hoge</h1>
    );
  }
}

モジュール全体のimport

  • 名前なし(default)exportしたモジュールをimportする
  • モジュール全体のimport
Blog.jsx
import React from 'react';
import Article from "./Article";
Article.jsx
const Article = (props) => {
  return (
    <div>Article</div>
  );
}
export default Article;

関数ごとのimport

  • 名前付きexportされたモジュールをimportする
  • {}内にimportしたい関数名
Hoge.js
import { Foo, Bar } from "./FooBar";
FooBar.js
export function Foo() {
  return (
    <h1>FOO</h1>
  );
}
export const Bar = () => {
  return (
    <h1>BAR</h1>
  );
}

別名import

  • 別名(エイリアス)をつけてimportできる
  • モジュール全体なら * as name
  • モジュール一部なら A as B
Blog.jsx
import React from 'react';
import * as AnotherName from './Article';
import { Foo as MyFoo } from './FooBar';
Article.js
const Article = (props) => {
  return (
    <div>Article</div>
  );
}
export default Article;
35
19
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
35
19