1.import,export——模組化
阿新 • • 發佈:2021-12-10
exp.js
export let a = 10; export let person = {name:'lily'} export function test(){console.log("hello");} export class Animal{ }
index.js
import {a} form './exp.js'; a = 100;//報錯 a是常量不能改 console.log(a) //10 =========== import {a,person} form './exp.js'; // a = 100;//報錯 a是常量不能改 //如果是基本型別,不能改,如果是物件如{a,person}就可以修改person.name = 'mickey';//物件可以修改屬性 console.log(a) //10 console.log(person.name) //mickey =========== import {a,person,Animal} form './exp.js'; let ani = new Animal(); console.log(ani)
匯入方式比較
index.js
import {exp} from './exp.js' console.log(exp.a); console.log(exp.Animal); ============= 一次性匯入某個檔案的所有模組並重新命名 import* as exp from './exp.js'; console.log(exp.a); console.log(exp.Animal);
將所有要匯入的元素放入default裡面
// exp.js let a = 10; let person = {name:'tom'}; function test(){console.log('hello')}; class Animal{} export default{ a,person,test,Animal } //default只能使用一次 // index.js import Exp from './exp.js'; console.log(Exp.a); console.log(Exp.Animal);