简体   繁体   English

如何在一个是模块的 Javascript 文件和另一个不是模块的 Javascript 文件之间共享函数和变量

[英]How to share functions and variables between one Javascript file that IS a module, and another Javascript file that is NOT a module

I have a project built using Javascript, jQuery, and Vite.js.我有一个使用 Javascript、jQuery 和 Vite.js 构建的项目。 I need to share functions and variables between one JS file that is a module, and another JS file that is not a module.我需要在一个作为模块的 JS 文件和另一个不是模块的 JS 文件之间共享函数和变量。 I'm specifically talking about whether the script tag has type="module" or not.我是在专门讨论脚本标签是否有type="module" Is this possible?这可能吗? I understand that if I could just set both script file types to "module", this would solve my problem and I could easily just use import/export syntax to share functions and variables.我知道如果我可以将两种脚本文件类型都设置为“模块”,这将解决我的问题,我可以轻松地使用导入/导出语法来共享函数和变量。 However, the 2nd script cannot be set to type="module" , as that would break snippets of code using certain dependencies.但是,第二个脚本不能设置为type="module" ,因为这会破坏使用某些依赖项的代码片段。

Just to illustrate what I'm saying -- here's an HTML file linked to two different JS files:只是为了说明我在说什么——这是一个链接到两个不同 JS 文件的 HTML 文件:

test.html测试.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

    <script type="module" src="./script1"></script>
    <script src="./script2"></script>
  </head>
  <body></body>
</html>

Now, script1.js has a variable we want to access from script2.js :现在, script1.js有一个我们想从script2.js访问的变量:

script1.JS脚本1.JS

const testVariable = "hello test variable";

script2.js script2.js

console.log(testVariable) //returns undefined

Obviously I can't use import/export or require since the 2nd script is not a module.显然我不能使用 import/export 或 require,因为第二个脚本不是模块。 Is there any way around this?有没有办法解决? I know that normally script files can access functions from script tags placed above them, but this doesn't seem to hold true for two different script types.我知道通常脚本文件可以从放置在它们上方的脚本标签访问函数,但这似乎不适用于两种不同的脚本类型。

I thought maybe I could use jQuery $.getScript per this S/O post , but as far as I can tell, that executes the requested script, but doesn't allow me to dynamically access specific variables and/or functions in the requested script?我想也许我可以根据这个S/O 帖子使用jQuery $.getScript ,但据我所知,它执行请求的脚本,但不允许我动态访问请求的脚本中的特定变量和/或函数?

Script modules do not implicitly create global variables.脚本模块不会隐式创建全局变量。 Variable, or named class or function names declared in a module are held in a closure created for module content, making them inaccessible by direct means from outside the module.在模块中声明的变量或命名类或函数名称保存在为模块内容创建的闭包中,使它们无法通过模块外部的直接方式访问。

Global Variable Usage全局变量用法

If the only issue is not being able to access variables exported by a module script, consider creating the variables as properties of the global window object in the module file instead of using variable declarations.如果唯一的问题是无法访问模块脚本导出的变量,请考虑在模块文件中将变量创建为全局window对象的属性,而不是使用变量声明。

This would change module declarations like这会改变模块声明,如

let brandName = "fooware";

to

window.brandName = "fooware";

This would then allow code in any script to access brandName as a variable.这将允许任何脚本中的代码将brandName作为变量进行访问。

Setters and Getters设置者和获取者

If a script module is to remain unchanged, you could set up an intermediate module to import exported items and republish them as setters and getters of a global object property name, using Object.defineProperty* EG如果脚本模块要保持不变,您可以使用Object.defineProperty* EG 设置一个中间模块来导入导出的项目并将它们重新发布为全局对象属性名称的 setter 和 getter

 <script type="module">
    import {brandName} from "./script1.js";
    Object.defineProperty(window, "brandName", {
       get() { return brandName; },
       set(newValue) { brandName = newValue; },
       enumerable: true
    });
 </script>

Note this kind of module (which doens't export any values) can be included inline in HTML using <script> tags without a src attribute.请注意,这种模块(不导出任何值)可以使用 <script> 标记内联包含在 HTML 中,而无需src属性。

* Object.defineProperties can be used to define multiple accessor properties at a time using slightly different syntax. * Object.defineProperties可用于使用稍微不同的语法一次定义多个访问器属性。

Deferring the non-modular script推迟非模块化脚本

Module scripts are deferred automatically without requiring the browser to load and parse then synchronously.模块脚本会自动延迟,无需浏览器同步加载和解析。 Try adding a defer attribute to the non-modular script so it is executed in the same order as module script tags provided in page source.尝试将defer属性添加到非模块化脚本,使其按照与页面源中提供的模块脚本标签相同的顺序执行。 When deferred, the script will not be parsed before body HTML has been parsed.延迟时,在解析正文 HTML 之前不会解析脚本。

Summary概括

JavaScript Modules are not designed to interact with non module script files. JavaScript 模块不是为与非模块脚本文件交互而设计的。 Refactoring non modular scripts into modules is generally preferred over more intrusive solutions.将非模块化脚本重构为模块通常比更具侵入性的解决方案更受欢迎。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在WebStorm中从一个JavaScript文件调用内部函数到另一个JavaScript文件? (使用module.exports除外) - How to call inner functions from one JavaScript file to another JavaScript file in WebStorm? (except using module.exports) JavaScript Module模式文件串联在一个文件中并使用其功能 - JavaScript Module pattern files concatenation in a one file and using their functions 如何在JavaScript模块中创建可混淆的变量和函数? - How to create obfuscatable variables and functions in a javascript module? Javascript文件或模块作用域仅变量 - Javascript file or module scope only variables 在node.js中,模块中的一个文件如何查看模块中另一个文件中的功能? - in node.js, how does one file in a module see functions in another file in the module? 如何将javascript变量/对象从一个文件复制到另一个文件 - How to copy javascript variables/objects from one file to another file 如何在节点模块和另一个JavaScript文件中声明数组(Mongodb) - How to Declare an array in a node module and another JavaScript file (Mongodb) 如何在javascript中从另一个文件调用模块导出函数 - How to call module export function from another file in javascript 如何从另一个文件 javascript 导入 Module.exports - How to import Module.exports from another file javascript 如何将模块模式 function 导出到另一个 JavaScript 文件 - How can I export module pattern function to another JavaScript file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM