React 笔记 export 和 import 基本语法

一、ES6的模块化的基本规则或特点

  • 每一个模块只加载一次, 每一个JS只执行一次, 如果下次再去加载同目录下同文件,直接从内存中读取。 一个模块就是一个单例,或者说就是一个对象;
  • 每一个模块内声明的变量都是局部变量, 不会污染全局作用域模块内部的变量或者函数可以通过export导出
  • 一个模块可以导入别的模块

二、几种import和export的基本语法

第一种导出

lib.js

let bar = "stringBar";
let foo = "stringFoo";
let sum = 1;
let fn0 = function() {
    console.log("fn0");
}

let fn1 = function() {
    console.log("fn1");
}

let fnSum = function() {
    sum = sum + 1;
    return sum;
}

export{ bar, foo ,fn0, fn1, fnSum}

main.js

import {bar,foo, fn0, fn1, fnSum} from "./lib";
import {fnSum as fnSum1} from "./lib";

console.log(bar+"_"+foo);
fn0(); //fn0
fn1(); //fn1

console.log(fnSum()); //2
console.log(fnSum()); //3
console.log(fnSum1()); //4

第二种导出

lib.js

let fn0 = function() {
    console.log("fn0");
};

let obj0 = {}

export { fn0 as foo, obj0 as bar};

main.js

import {foo, bar} from "./lib";

foo(); //fn0

bar.name = '123';
console.log(bar);//Object {name: "123"}

第三种导出的方式

lib.js

export let foo = ()=> {console.log("fnFoo") ;return "foo"},bar = "stringBar";

main.js

import {foo, bar} from "./lib";
console.log(foo());
console.log(bar);

第四种导出的方式

lib.js

export default "string"

main.js

import defaultString from "./lib";
console.log(defaultString);

第五种导出方式

lib.js

let fn = () => "string";
export {fn as default};

main.js

import defaultFn from "./lib";
console.log(defaultFn());

第六种导出方式

other.js

export let foo = "stringFoo";
export let fnFoo = function() {console.log("fnFoo")};

lib.js

export * from "./other";

main.js

import {foo, fnFoo} from "./lib";
console.log(foo);
console.log(fnFoo());

第七种导出方式

import * as obj from "./lib";
console.log(obj);

三、 ES6导入的模块都是属于引用

lib.js

export let counter = 3;
export function incCounter() {
    counter++;
}
export function setCounter(value) {
    counter = value;
}

main.js

import { counter, incCounter ,setCounter} from './lib';

// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4
setCounter(0);
console.log(counter); // 0
posted @ 2020-09-07 14:36  silentmuh  阅读(1701)  评论(0编辑  收藏  举报
Live2D