web:js的模块导出/导入

发布于:2025-08-03 ⋅ 阅读:(14) ⋅ 点赞:(0)

一般web页面中,html文件通过标签script引用js文件。但是js文件之间的引用要通过import/exprot进行导入/导出,同时还要在html文件中对js文件的引用使用type属性标注。

在下面的例子中,

html页面

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>

<body>
    <form>
        <input id="username" name="username" type="text">
        <input id="age" name="age" type="text">
        <input id="b1" type="submit" value="提交">
        <input id="b2" type="button" value="单击事件">
    </form>

    <br>
    <br>
    <br>

    <table width="800px" border="1" cellspacing="0" align="center">
        <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>分数</th>
            <th>评语</th>
        </tr>
        <tr align="center">
            <th>001</th>
            <th>张三</th>
            <th>90</th>
            <th>优秀</th>
        </tr>
        <tr id='last' align="center">
            <th>003</th>
            <th>赵四</th>
            <th>85</th>
            <th>良好</th>
        </tr>
    </table>
    
    <!-- 调用的js文件使用到export,import等高级技能时,必须使用属性type='module'标注。 -->
    <script src="../../js/常见事件优化/常见事件优化.js" type="module"></script>
</body>
</html>

html调用“常见事件优化.js”文件。

// 导入变量,方法。
import {content, printConsoleLog} from "./打印日志.js";

console.log(content);

// 定义函数。
let mouseEnter = function (event) {
    // window.alert('鼠标进入事件');
    // console.log('鼠标进入事件');
    printConsoleLog('鼠标进入事件');
};

function mouseLeave(event) {
    // window.alert('鼠标离开事件');
    // console.log('鼠标离开事件');
    printConsoleLog('鼠标离开事件');
    printConsoleLog(event.type);
};

const button = document.querySelector('#b1');
button.addEventListener('click', function () {
    // window.alert('点击submit按钮');
    // console.log('点击submit按钮');
    printConsoleLog('点击submit按钮');
});

// 根据id获取控件,绑定事件。
const inputController = document.querySelector('#last');
inputController.addEventListener('mouseenter', mouseEnter);
inputController.addEventListener('mouseleave', mouseLeave);

被导入的“打印日志.js”文件,文件中通过export关键字标注导出被调用的方法和变量。


export function printConsoleLog(msg) {
    console.log(msg);
}

export let content = 'abc';