LoginSignup
1
1

More than 5 years have passed since last update.

import,exportの書き方について

Posted at

「Code Grid」で書かれていたimportとexportの指定の書き方について参考になったので、備忘録も兼ねて書きたいと思います。

default exportsの書き方

export default [関数]

export
export default function (world) {
  console.log('hello ' + world);
}

import [変数名] from [import先のパス]

import
import test from './export';
test('world'); // hello world

export default [class]

export
export default class {
  constructor() {}
  hello(world) {
    console.log('hello ' + world);
  }
}

import [変数名] from [import先のパス]

import
import Test from './Export';
const test = new Test();
test.hello('world'); // hello world

named exportsの書き方

export [変数]

export
export const test = 'hello world';

import { [exportで書いた変数] } from [import先のパス]

import
import { test } from './export';
console.log(test); // hello world

import { [exportで書いた変数 as 任意の変数] }

import
import { test as Test } from './export';
console.log(Test); // hello world

export [変数]

export
export const num1 = 1;
export const num2 = 2;
export const num3 = 3;
export const num4 = 4;

import { [exportで書いた変数, exportで書いた変数, ...] } from [import先のパス]

import
import [ num1, num2, num3, num4 ]  from './export';
console.log(num1); // 1
console.log(num2); // 2
console.log(num3); // 3
console.log(num4); // 4

上記を1つの変数[Num]にまとめた書き方

import
import * as Num from './export';
console.log(Num.num1); // 1
console.log(Num.num2); // 2
console.log(Num.num3); // 3
console.log(Num.num4); // 4
1
1
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
1
1