简体   繁体   中英

how to share variable between more than One file in nodejs

// app.js

var myvar = 1  
module.exports = {myvar}; 

// another in my project

var mynewvar =require("../app.js")
console.log(mynewvar.myvar); // undefined ? 

I need to make var is global in all project ? I'm try global but the same issue can any one help me?

My only guess is you might not have the path to app.js right. This works:

// app.js

var myvar = 1  
module.exports = {myvar}; 

// index.js

var mynewvar =require("./app.js")
console.log(mynewvar.myvar);

Here's a repl.it that shows it works:

https://repl.it/repls/CruelMonstrousArchives

Maybe you're doing something different than this?

you can easily achieve this, either in es6(lib.js) way or es5(lib2.js) way.

live example: https://codesandbox.io/embed/mo8z2ooovj

export module es6 lib.js :

const myvar = 1;
export default myvar;`

export module es5 lib2.js :

var myvar2 = 2;
module.exports = myvar2;`

into another file you can import the modules and display the values like so, i use a component:

 import myvar from "./lib";
 import myvar2 from "./lib2";

 // you can use the imported values here as you need


 // e.g.
 function App() {
   return (
     <div className="App">
       <h1>Hello CodeSandbox</h1>
       <p>value from lib.js {myvar}</p>
       <p>value from lib2.js {myvar2}</p>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);`

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