LoginSignup
3
0

More than 1 year has passed since last update.

[JavaScript] named export と default export の違い

Posted at

export とか import の構文をES Modulesと呼びます。
ES Modulesを使うために、Deno 環境を用意するとよいです。

Node.js でも package.json 記載すればうまく動きます。
この記事ではどちらでも動かしてみます。

fileA.js
export const funcA = () => {
  console.log('funcA output')
};

これが named export 。関数名付きでファイルからexportしています。

fileB.js
const funcB = () => {
  console.log('funcB output')
};

export default funcB;

これが default export 。名前なしでファイルからexportしています。

使い方はそれぞれこんな感じ。全て同一ディレクトリ内に配置してください。

index1.js
import { funcA } from './fileA.js'
import funcB from './fileB.js'
console.log('index.js');  // index.js
funcA();                  // funcA output
funcB();                  // funcB output

> deno run index1.js

上記コマンドで、コメントに示している通りの出力が行われます。

これらの名前を変更して利用する場合は次のようにします。

index2.js
import { funcA as funcA1 } from './fileA.js'
import funcB1 from './fileB.js'
console.log('index.js');  // index.js
funcA1();                  // funcA output
funcB1();                  // funcB output

> deno run index2.js

funcAは名前が指定されているので別名で定義するときは as を使います。

funcBの方は、fileBから出力されているってだけで名前なしなので、別名の変数に代入するだけで使えます。

Node.js で ES Modules を動かすためには、.js の拡張子の場合、package.json の記載が必要です。

package.json
{ "type": "module" }

> node .\index1.js
> node .\index2.js

それぞれのコマンドで動作確認できます。

参考

Node.js で ES Modules 記法を動かしてみる - Neo's World
https://neos21.net/blog/2020/09/02-02.html

以上です。

3
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
3
0