创建一个js文件。
//Say 模块
export function Say(words){
alert(words);
}
H5调用模块
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>ES 6 Module</title>
</head>
<body>
<script type="module">
import {Say} from "./OneModuleOneFile.js";
Say('你好,module')
</script>
</body>
</html>
打开页面
注意:H5的script type需要指定module
export function SayHello(){
console.log('SayHello:Hello')
}
export function SayES6(){
console.log('SayES6:ES6')
}
// export default function SayDefault(){
// console.log('SayDefault:Default...')
// }
//default还可以这样
export default {
hi(){
console.log('df-hi')
},
hello(){
console.log('df-hello')
}
}
function SayFn1(){
console.log('SayFn1:Fn1')
}
function SayFn2(){
console.log('SayFn2:Fn2')
}
function SayFn3(){
console.log('SayFn3:Fn3')
}
const fnVersion = '3.0';
//先声明函数或变量再导出
export {SayFn1,SayFn2,SayFn3,fnVersion}
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>ES 6 Module</title>
</head>
<body>
<script type="module">
// import SayDefault from "./MultiModuleOneFile.js";
import {SayHello,SayES6,default as dff,SayFn1,SayFn2,SayFn3,fnVersion} from "./MultiModuleOneFile.js";
dff.hi();
SayES6();
console.log('fnVersion:',fnVersion)
</script>
</body>
</html>
打开页面,打开控制台:
可以看到运行结果没啥问题。
'use strict';
export class Say{
//构造函数
name;
constructor(name){
this.name = name;
}
hi(){
console.log('Say.hi');
}
hello(){
console.log('Say.hello');
}
words(words){
console.log('Say.',words,' name:',this.name);
}
}
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Object Module</title>
</head>
<body>
<script type="module">
import {Say} from "./ObjectModuleFile.js";
let say=new Say('我是构造参数');
say.words('我是words参数');
</script>
</body>
</html>
打开页面结果:
https://www.leftso.com/article/2408031549453932.html