首页 > 解决方案 > 多次导入 ES6 模块?

问题描述

我正在努力了解浏览器究竟是如何处理 ES6 模块的。我想,这些模块只会在第一次导入时执行([modules: javascript.info][1].

假设我有以下项目结构:

js
  admin.js
  customers.js
  index.js 
customers.html 
index.html

两者都index.js导入customers.js同一个模块admin.js。当我导入index.jsindex.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 )

标签: javascriptecmascript-6module

解决方案


正如上面 Felix 所说,每个页面渲染/重新渲染都会重新加载所有资产。这是单页应用程序和多页应用程序之间的区别。您正在使用 MPA,因此您需要在页面之间进行某种形式的数据持久性,例如在数据服务器端建立数据库并在每次页面加载时请求它,或者将必要的持久化数据放置在类似页面localStorage之间sessionStorage的访问。


推荐阅读