JavaScript

モジュール

JavaScript

import/export、ES Modules

ES Modules

import / export の構文

modules.js javascript
// === math.js(エクスポート側)===

// 名前付きエクスポート
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export class Calculator { /* ... */ }

// デフォルトエクスポート(1ファイルに1つ)
export default class App { /* ... */ }

// まとめてエクスポート
const multiply = (a, b) => a * b;
const divide   = (a, b) => a / b;
export { multiply, divide };
export { multiply as mul, divide as div }; // リネーム

// === main.js(インポート側)===

// 名前付きインポート
import { PI, add } from './math.js';
import { multiply as mul } from './math.js';

// デフォルトインポート
import App from './app.js';

// デフォルト + 名前付き
import App, { PI, add } from './math.js';

// 全て
import * as Math from './math.js';
Math.PI; Math.add(1, 2);

// 動的インポート(コード分割)
const { add } = await import('./math.js');

モジュールパターン

再エクスポート、バレルファイル、循環参照

index.js javascript
// バレルファイル(index.js)— 複数モジュールをまとめて公開
export { Button }   from './Button.js';
export { Input }    from './Input.js';
export { Modal }    from './Modal.js';
export { default as Card } from './Card.js';

// 使用側
import { Button, Input, Modal } from './components'; // index.js省略可

// 再エクスポート(全て)
export * from './utils.js';
export * as utils from './utils.js'; // 名前空間付き

// 条件付きインポート(動的)
async function loadFeature(name) {
    const module = await import(`./features/${name}.js`);
    return module.default;
}

// import.meta
console.log(import.meta.url);  // 現在のファイルのURL
console.log(import.meta.env);  // 環境変数(Vite等)