简体   繁体   中英

Read/Use variables from another javascript file

If I import a js file like this :

const importedFile = require( './file1');

I can see all my functions and console logs of file1 running, but I can't run or use a specific variable

If I console.log( importedFile ) I get this : {} empty object !

How to get all variables from file1.js ?

JavaScript modules are self-contained environments with their own scope.

Only explicitly exported values are available outside of the module.

So, if you want something in ./file1 to be available in importedFile , then you need to include it in the exports:

const value = "Hello, world";

function thisIsAFunction() {
    console.log(value);
}

module.exports = {
    thisIsAFunction
}

Then you can:

const importedFile = require( './file1');
importedFile.thisIsAFunction();

I figured it out, in file1 I can export variables like this :

function thisIsAFunction() {
    let var1 = { qty: 123 }
    let var2 = { qty: 123 }
    let var3 = { qty: 123 }

    return [ var1, var2, var3 ];
}
module.exports = {
    thisIsAFunction
}

Then read/use the first variable like this:

let importedValue= importedFunct.thisIsAFunction()

console.log(  importedValue[0][0].qty)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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