7

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 4

6

You 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

Sign up to request clarification or add additional context in comments.

2 Comments

I have tried using this, but as I have said in another post, using this method gives me an error. When I run my code in npm, it says that the { in import { variable } is an unexpected token.
4

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.

3 Comments

When I link to both files, npm still says that variable is not defined.
What does npm have to do with this? What does your build process look like?
Basically, I'm trying to add more code to this project on Github. In order to run the code, I have to type in npm run dev in the directory of the project.
1

You'd use import/export syntax.

In first.js:

let newName = "New Name";
export { newName };

In second.js:

import { newName } from "./../first.js";

5 Comments

Using this method gives me an error. When I run my code in npm, it says that the { in import { variable } is an unexpected token.
Oh, you're using NPM/Node? Use require instead.
so do I replace import with require, or do I type more?
in your consumer file like this; const variableName = require('./sourceFile');
I am pretty sure you cannot assign to 'newName' because it is an import, even if you use let
-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.