javascript - 多次导入 ES6 模块?
问题描述
我正在努力了解浏览器究竟是如何处理 ES6 模块的。我想,这些模块只会在第一次导入时执行([modules: javascript.info][1].
假设我有以下项目结构:
js
admin.js
customers.js
index.js
customers.html
index.html
两者都index.js
导入customers.js
同一个模块admin.js
。当我导入index.js
的index.html
名称admin
从“John”更改为“Pete”并按预期记录时。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Modules</title>
</head>
<body>
<nav><a href="customers.html">Customers</a></nav>
<h1>Homepage</h1>
<script type="module" src="js/index.js"></script>
</body>
</html>
在customers.html中,我希望管理员的名字也是“Pete”:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Customers</title>
</head>
<body>
<nav><a href="index.html">Home</a></nav>
<h1>Customers</h1>
<script type="module" src="js/customers.js"></script>
</body>
</html>
但不是“Pete”,而是再次记录“John”。
我使用的模块:
// admin.js
export let admin = {
name: "John",
};
//index.js
import { admin } from "./admin.js";
admin.name = "Pete";
console.log(admin.name); // Pete
// customers.js
import { admin } from "./admin.js";
console.log(admin.name); // Pete
[1]:https ://javascript.info/modules-intro#a-module-code-is-evaluate-only-the-first-time-when-imported )
解决方案
正如上面 Felix 所说,每个页面渲染/重新渲染都会重新加载所有资产。这是单页应用程序和多页应用程序之间的区别。您正在使用 MPA,因此您需要在页面之间进行某种形式的数据持久性,例如在数据服务器端建立数据库并在每次页面加载时请求它,或者将必要的持久化数据放置在类似页面localStorage
之间sessionStorage
的访问。
推荐阅读
- node.js - 从 onelogin 进行身份验证并重定向到仪表板
- r - 如何从 R 中的另一个列表列表中删除列表列表?
- python - Scrapy - 重定向到验证码页面时抓取页面
- bash - BASH - OPTARG 中的 getopts 正则表达式
- react-native - TypeError:null 是一个对象(评估'reactNativeImagCropPicker.default.openPicker')
- opengl - LWJGL3 和 OpenGL 是否需要着色器才能渲染?
- typescript - 如何在新的组合 API 中键入计算属性?
- amazon-cognito - 将 Github 身份提供商添加到 AWS Cognito
- php - 使用 php 在另一个页面上使用 header() 函数提交 jquery 后重定向页面
- security - 使用动态用户进行 RabbitMQ 用户身份验证