简体   繁体   English

限制js文件内容的范围

[英]limit the scope of contents in js file

I recently encountered a situation where i have A.js, B.js and C.js .我最近遇到了一种情况,我有 A.js、B.js 和 C.js。 All those JS files importing a same module.所有这些 JS 文件都导入了相同的模块。 ( ex: const hello = require ("hello"); ) . (例如: const hello = require ("hello"); )。 While running them together i get following SyntaxError in the console一起运行它们时,我在控制台中遵循 SyntaxError

Uncaught SyntaxError: Identifier 'home' has already been declared

I'm loading those JS files from HTML using Script tag like below我正在使用如下所示的 Script 标签从 HTML 加载这些 JS 文件

<script src="../js/A.js"></script>
<script src="../js/B.js"></script>
<script src="../js/C.js"></script>

Moving content of each js file into { } curly braces is one option to fix the SyntaxError.将每个 js 文件的内容移动到{ }大括号中是修复 SyntaxError 的一种选择。

But i want to know whether this({}) is right solution or do we have any other better solutions to address this situation但我想知道这({})是否是正确的解决方案,或者我们是否有其他更好的解决方案来解决这种情况

A common solution would be to use an IIFE (Immediately Invoked Function Expression).一个常见的解决方案是使用IIFE (立即调用函数表达式)。 Basically, wrap your code in a function and call it at the same time.基本上,将您的代码包装在一个函数中并同时调用它。 This both protects the code's scope and prevents people viewing the page from accessing your data in their developer tools.这既保护了代码的范围,又防止了查看页面的人在他们的开发人员工具中访问您的数据。

(function() {
    /* your code here */
})();

A more modern, and arguable more correct, solution would be to use JavaScript modules .一个更现代、更有争议的更正确的解决方案是使用JavaScript 模块 Then you can use import instead of require , and you can organize your code a bit more like you would expect from Python or Java.然后您可以使用import而不是require ,并且您可以更像您对 Python 或 Java 所期望的那样组织您的代码。

<!-- index.html -->
<script type="module" src=".../module.js"></script>
<script type="module" src=".../src1.js"></script>
<script type="module" src=".../src2.js"></script>
// module.js
export const MESSAGE = "Hello, world!";
// src1.js (src2.js looks basically the same)
import { MESSAGE } from ".../module.js";
console.log("src1 says:", MESSAGE);

However, a few browsers do not support modules.但是,一些浏览器不支持模块。 To get around that, you could use a bundler (such as Webpack , Parcel , or Rollup ) to compile your project.为了解决这个问题,您可以使用捆绑程序(例如WebpackParcelRollup )来编译您的项目。 These also provide other features (such as code minification).这些还提供其他功能(例如代码缩小)。 But for a small project, using a bundler may not be worth the effort (though learning to use them will be helpful if you go into web development).但是对于一个小项目,使用 bundler 可能不值得付出努力(尽管如果你进入 web 开发,学习使用它们会很有帮助)。

Moving content of each js file into { } curly braces is one option to fix the SyntaxError.将每个 js 文件的内容移动到 { } 大括号中是修复 SyntaxError 的一种选择。

Yes.是的。 That syntax error is only caused by redeclaring a variable that was declared with let or const , and these are block scoped, so introducing a new block fixes that.该语法错误仅是由重新声明用letconst声明的变量引起的,并且这些是块范围的,因此引入新块可以解决该问题。

Note that var s and function s will leak through it though (but redeclaring them won't cause an error¹):请注意, var s 和function s 会通过它泄漏(但重新声明它们不会导致错误¹):

 {
    function test() { }
 }

 test();

¹ as you usually want strong encapsulation as redeclaring global variables usually causes unpredictable side effects, I'd go with an IIFE, or use ES modules. ¹ 因为您通常需要强封装,因为重新声明全局变量通常会导致不可预测的副作用,我会使用 IIFE 或使用 ES 模块。

It is always a good habit to have your code wrapped inside an anonymous function as follows将您的代码包裹在匿名函数中始终是一个好习惯,如下所示

 (function(){ /* all your variables, and functions ... everything goes in here */ })();

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM