Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access variables from another file?

People also ask

How do I pass a variable from one JavaScript file to another?

There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.

How access variable from another file in react JS?

To import a variable from another file in React:Export the variable from file A , e.g. export const str = 'hello world' . Import the variable in file B as import {str} from './another-file' .

How is a variable accessed from another file Mcq?

The extern keyword is used to indicate that the variable can be accessed by another file.


As Fermin said, a variable in the global scope should be accessible to all scripts loaded after it is declared. You could also use a property of window or (in the global scope) this to get the same effect.

// first.js
var colorCodes = {

  back  : "#fff",
  front : "#888",
  side  : "#369"

};

... in another file ...

// second.js
alert (colorCodes.back); // alerts `#fff`

... in your html file ...

<script type="text/javascript" src="first.js"></script> 
<script type="text/javascript" src="second.js"></script> 

You can export the variable from first file using export.

//first.js
const colorCode = {
    black: "#000",
    white: "#fff"
};
export { colorCode };

Then, import the variable in second file using import.

//second.js
import { colorCode } from './first.js'

export - MDN


I did like what answer above said but although, it didn't worked with me

because I was declaring these variables inside JQuery $( document ).ready()

so make sure you declare your variables inside the <script> tag not somewhere else


Using Node.js you can export the variable via module.

//first.js
const colorCode = {
    black: "#000",
    white: "#fff"
};
module.exports = { colorCode };

Then, import the module/variable in second file using require.

//second.js
const { colorCode } = require('./first.js')

You can use the import and export aproach from ES6 using Webpack/Babel, but in Node.js you need to enable a flag, and uses the .mjs extension.


This should work - define a global variable in firstfile and access it from secondfile:

<script src="/firstfile.js"></script>
<script src="/secondfile.js"></script>

firstfile.js:

var colors = {
   text:'#000000',
   background:'#aaaaaa',
   something_else:'blue'
};

secondfile.js:

do_something_with(colors.background);

Note that the order in which you load the script files is significant for some browsers (IE6 for sure, maybe others)


I came across amplify.js. It's really simple to use. To store a value, let's call it "myValue", you do:

amplify.store("myKey", "myValue")

And to access it, you do

amplify.store("myKey")

If you store your colorcodes in a global variable you should be able to access it from either javascript file.