LoginSignup
1

More than 1 year has passed since last update.

【JavaScript・TypeScript】export default

Posted at

export default とは

.jsファイルからあるコンポーネントをexportするとき、export default コンポーネントとすることで、他のファイルでそのコンポーネントをimportするときに任意の名前で使うことができる、というものです。例を示します。

使用例

Discord.jsでDiscordのボットを開発しているときの例。TypeScript要素ありますが内容わからなくても大丈夫です。
messageCreateというeventと、!shutdownで動作を停止する関数handlerをexport defaultでexportしています。

shutdown.ts
import { Message } from "discord.js";
const prefix = require('../config/config.json').prefix;

const event = 'messageCreate';

const handler = async(message: Message) => {
  if(message.content === `${prefix}shutdown`){
    await message.channel.send("Goodbye!");
    await console.log("shutdown...");
    await process.exit();
  }
}

//ここに注目
export default {event,handler};

これを他のファイルでimportするときに、名前を好きなようにつけることができます。index.tsというファイルで読み込むとして、

import shutDown from "./shutdown";

でも

import aaa from "./shutdown";

でも問題なくimportできるのです。ファイル内で固有のコンポーネント名を持つことができるので便利だという話ですね。

配列的なexportなども可

例えば複数機能を持つボットを開発している時。各機能ごとにファイルで小分けして開発することになると思います。
その時、ある.tsファイルで一度すべてのファイルのコンポーネントを集合させて、まとめて実行ファイルにexportすると分かりやすくなります。

// コマンドのファイルをインポート
import timeNotificaiton from "./time";
import shutDown from "./shutdown";

// まとめてエクスポート
export default [
  timeNotificaiton,shutDown,
]

1つのファイル内には一行のみ

export defaultを1つのファイルに複数行書くとエラーになります。勝手に配列に統合するといった機能はないので注意が必要です。

// コマンドのファイルをインポート
import timeNotificaiton from "./time";
import shutDown from "./shutdown";

// エラー
export default timeNotification;
export default shutDown;

今回は以上です。

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
1