import、exportについて。
前提
今回は2つのファイルを使います。
以下の構成になります。
.
├── index.js
└── test.mjs
index.js が test.mjs を読み込む事を想定しています。
基本
パターン1
export
出力側 test.mjs になります。
export する対象を { } で囲みます。
function sample(){
return 'hello!!'
}
export {sample};import
読み込み側 index.js になります。
import する対象を { } で囲みます。なお、読み込みは export された名称と同じにする必要があります。
今回は “sample” という名称の関数が export されているので、import も “sample” にしています。
import {sample} from './test.mjs'
console.info(sample());結果
node index.js
hello!!パターン2
export
test.mjs を修正します。関数の前に export を記載しても同じ結果になります。
export function sample(){
return 'hello!!'
}複数パターン
同じ関数名のものを同時にexport出来ません。関数を変数に格納し、別々の変数名でexportする事が出来ます。
export
test.mjs
const func_01 = function sample(){
return 'hello!!'
}
const func_02 = function sample(){
return 'hello000!!'
}
export {func_01, func_02};import
index.js
import {func_01, func_02} from './test.mjs'
console.info(func_01());
console.info(func_02());結果
node index.js
hello!!
hello000!!エクスポートデフォルト
よく見る “export default” について。
パターン1
基本になります。
export
test.mjs。“export default” を使う場合、{ } は不要です。
function default_func(){
return 'default_func!!!'
}
export default default_func;import
index.js。“export default” を使う場合、{ } は不要です。
import default_func from './test.mjs'
console.info(default_func());結果
node index.js
default_func!!!パターン2
importの名前を変更する事が可能です。
import
index.js。読み込み名を任意に変えても結果は同じになります。test.mjsの内容は変えてません。
import my_func from './test.mjs'
console.info(my_func());ミックスパターン
“export default” と通常のexportを両方行う事が出来ます。
export
test.mjs
function default_func(){
return 'default_func!!!'
}
export function func(){
return 'func!!!'
}
export default default_func;import
index.js
import my_func, {func} from './test.mjs'
console.info(my_func());
console.info(func());通常の export に対する importは { } ありで、export default は { } なしとなります。
結果
node index.js
default_func!!!
func!!!アスタリスク
” * ” (アスタリスク)を使うと全ての export を import 出来ます。
export
test.mjs
export function func(){
return 'func!!'
}
export const sample = 'sample!!';import
index.js
import * as my_module from './module/test.mjs'
console.info(my_module.func());
console.info(my_module.sample);結果
node index.js
func!!
sample!!最後に
export の場合は { } をつけてimportする。export default の場合、{ } は不要。