import 引用方式

2022-01-10  本文已影响0人  Petricor

注:js想要使用import 引用需要在 script标签上添加属性type="module"


<!DOCTYPE html>
<html>
<script src="js/index.js" type="module"></script>
<!-- 引入组件库 -->
</html>

1. 具名导入 import utility from "utility.js" export default 导出

// utility.js 导出模块 
let e1 = 'export 1';
let e2 = 'export 2';
function e3() {
    return 'export 3';
};
let e4 = {
    name: 'zhangha',
    sex: 25,
};
export default {  e1,  e2,  e3,  e4 };
 //使用模块的index.js
import utility from "./utility.js";
console.log(utility.e1);
console.log(utility.e2);
console.log(utility.e3);
console.log(utility.e4);
#index.js运行结果
export 1
export 2
 ƒ e3() {
    let e = 'export 3';
    return e
}
{name: 'zhangha', sex: 25}
1.1 如果在utility .js再添加一个export default
  let e4 = 'export e4';
  let e5='export e5';
  export default  e4
  export default  e5
#index.js运行结果
    SyntaxError: .../utility .js: 
    Only one default export allowed per module. (10:0)
   9 | let e5='export e5';
> 10 | export default  e5

2. import { e1 ,e2 } from "utility.js"; export 导出

// utility.js 导出模块 
let e1 = 'export 1';
let e2 = 'export 2';
function e3() {
    let e = 'export 3';
    return e
};
let e4 = {
    name: 'zhangha',
    sex: 25,
};

export { e1 }
export { e2 }
export { e3 }
export { e4 }
//或者 export { e1 , e2 , e3 , e4}

  //使用模块的index.js
import { e1 ,e2 ,e3, e4} from "./utility.js";
console.log(e1);
console.log(e2);
console.log(e3);
console.log(e4);
2.1 import * as utility from "utility.js";
  //使用模块的index.js
import  * as utility  from "./utility.js";
console.log(utility.e1);
console.log(utility.e2);
console.log(utility.e3);
console.log(utility.e4);
2.2 import { e1 as alias } from "utility";
//使用模块的index.js
import { e1 , e2 as alias2, e3 as alias3, e4 as alias4 } from "./utility.js";

console.log(e1);
console.log(alias2);
console.log(alias3);
console.log(alias4);
#index.js运行结果
export 1
export 2
 ƒ e3() {
    let e = 'export 3';
    return e
}
{name: 'zhangha', sex: 25}

3. import e3, { e1, e2, e4 } from "./utility.js"; default语法联合导入

// utility.js 导出模块 
let e1 = 'export 1';
export let e2 = 'export 2'; // 直接定义

function e3() {
    let e = 'export 3';
    return e
};
let e4 = {
    name: 'zhangha',
    sex: 25,
};

export { e1 }
export { e4 }
export default e3
//使用模块的index.js
import e3, { e1, e2, e4 } from "./utility.js";

console.log(e1);
console.log(e2);
console.log(e3);
console.log(e4);

3.1 或者 import e3, * as utility from "./utility.js";
import e3, * as utility  from "./utility.js";
console.log(utility.e1);
console.log(utility.e2);
console.log(e3);
console.log(utility.e4);

#index.js运行结果
export 1
export 2
 ƒ e3() {
    let e = 'export 3';
    return e
}
{name: 'zhangha', sex: 25}

参考: ES6 export && export default 差异总结
MDN import 导入默认值

上一篇下一篇

猜你喜欢

热点阅读