注: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 导出
- 在一个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 导出
- 在一个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);
- 2.0 、2.1 、2.2 打印结果
#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);
- 3.0 、3.1 打印结果
#index.js运行结果
export 1
export 2
ƒ e3() {
let e = 'export 3';
return e
}
{name: 'zhangha', sex: 25}
网友评论