エクスポートとインポート(defaultエクスポート)
- クラスや定数をエクスポートしてインポートしたらインポートしたファイルで使える
- デフォルトエクスポートは1ファイル1つの値のみ(なのでimportで違う定数名にしても読み込める)
export default Animal;
import Animal from "./animal";
エクスポートとインポート(複数エクスポート)
export {dog1,dog2};
import {dog1,dog2} from "./dogData";
パッケージをインポート
import chalk from "chalk";
import readlineSync from "readline-sync";
総合演習
import { dog1, dog2 } from "./data/dogData";
console.log("---------");
dog1.info();
console.log("---------");
dog2.info();
import readlineSync from "readline-sync";
import Dog from "../class/dog";
const dog1 = new Dog("レオ", 4, "チワワ");
const name = readlineSync.question("名前を入力してください: ");
const age = readlineSync.questionInt("年齢を入力してください: ");
const breed = readlineSync.question("犬種を入力してください: ");
const dog2 = new Dog(name, age, breed);
export { dog1, dog2 };
import chalk from "chalk";
import Animal from "./animal";
class Dog extends Animal {
constructor(name, age, breed) {
super(name, age);
this.breed = breed;
}
info() {
this.greet();
console.log(chalk.yellow(`名前は${this.name}です`));
console.log(chalk.bgCyan(`犬種は${this.breed}です`));
console.log(`${this.age}歳です`);
const humanAge = this.getHumanAge();
console.log(`人間年齢で${humanAge}歳です`);
}
getHumanAge() {
return this.age * 7;
}
}
export default Dog;
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log("こんにちは");
}
info() {
this.greet();
console.log(`名前は${this.name}です`);
console.log(`${this.age}歳です`);
}
}
export default Animal;