Let's say that I have two files that are in separate directories:
/folder1/first.js
/folder1/folder2/second.js
first.js
contains a variable called newName
. Would it be possible to access it in second.js
? (and how)?
EDIT: The HTML file is located in the same directory as first.js
.
Let's say that I have two files that are in separate directories:
/folder1/first.js
/folder1/folder2/second.js
first.js
contains a variable called newName
. Would it be possible to access it in second.js
? (and how)?
EDIT: The HTML file is located in the same directory as first.js
.
4 Answers
Reset to default 6You should use export function in the first.js file and use require in second.js to access that variable.
For example If you have var named first in first .js.
const first = {
name: 'dharmik',
age: '21'
}
Export it like this:
export { first };
And then import in second.js like this:
import { first } from './first.js'
And then you can use the variable in second.js.
console.log(first.name);
//dharmik
Assuming you are just linking static HTML files with <script>
tags, then they will share their global scope. In other words: yes, second.js
will be able to access the top-level variables from first.js
, assuming they were liked in that order. Directories have no bearing on the behavior.
You'd use import
/export
syntax.
In first.js
:
let newName = "New Name";
export { newName };
In second.js
:
import { newName } from "./../first.js";
Technically yes this is possible, if you are going to access it from "second.js"
<script src="../first.js">
//code here that uses the global variable from first.js
</script>
The .. allows for file directory traversal, by going up 1 directory.