Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limit the scope of contents in js file

Tags:

javascript

I recently encountered a situation where i have A.js, B.js and C.js . All those JS files importing a same module. ( ex: const hello = require ("hello");) . While running them together i get following SyntaxError in the console

Uncaught SyntaxError: Identifier 'home' has already been declared

I'm loading those JS files from HTML using Script tag like below

<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.

But i want to know whether this({}) is right solution or do we have any other better solutions to address this situation

like image 248
amkon Avatar asked Sep 05 '25 18:09

amkon


2 Answers

A common solution would be to use an IIFE (Immediately Invoked Function Expression). 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. 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.

<!-- 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. 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).

like image 118
jirassimok Avatar answered Sep 08 '25 06:09

jirassimok


Moving content of each js file into { } curly braces is one option to fix the 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.

Note that vars and functions will leak through it though (but redeclaring them won't cause an error¹):

 {
    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.

like image 43
Jonas Wilms Avatar answered Sep 08 '25 07:09

Jonas Wilms