首先安装工具Visual Studio Code,安装插件。或者导入插件信息配置,配置好环境后,创建一个js文件写两个方法,方法用export导出
//简单信息
export function simpleMessage(msg){
console.log(msg);
}
//复杂信息
export function complexMessage(msg){
console.log(new Date()+": "+msg);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>快速入门</title>
</head>
<body>
<div id="app">
<button id="but">
点击展示信息
</button>
<script type="module">
import {simpleMessage} from './messages.js';
document.getElementById('but').onclick=function(){
simpleMessage('helloworld');
}
</script>
</div>
</body>
</html>
在html文件中<script type="module">必须要加类型module。然后导入方法及所在的js文件,获取按键元素,添加动作调取方法。
2、js文件多方法批量导出及方法重命名
//简单信息
function simpleMessage(msg){
console.log(msg);
}
//复杂信息
function complexMessage(msg){
console.log(new Date()+": "+msg);
}
//批量导出及方法重命名
export {simpleMessage as sm,complexMessage as cm}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>快速入门</title>
</head>
<body>
<div id="app">
<button id="but">
点击展示信息
</button>
<script type="module">
import {cm} from './messages.js';
document.getElementById('but').onclick=function(){
cm('helloworld');
}
</script>
</div>
</body>
</html>
3、默认导出,在导入可以随意命名
//简单信息
function simpleMessage(msg){
console.log(msg);
}
//复杂信息
function complexMessage(msg){
console.log(new Date()+": "+msg);
}
//批量导出及方法重命名
export default{simpleMessage,complexMessage}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>快速入门</title>
</head>
<body>
<div id="app">
<button id="but">
点击展示信息
</button>
<script type="module">
import messageMethods from './messages.js';
document.getElementById('but').onclick=function(){
messageMethods.complexMessage('helloworld');
}
</script>
</div>
</body>
</html>
默认导出必须要加default关键字,导入时可以随意命名导入名,调用时导入名+方法名。