简体   繁体   中英

Javascript, require var

 helper.js

I usually program in Ruby. I want to get this info:

 var shopInfo =
  {
    "shopName": "The Coffee Connection",
    "address": "123 Lakeside Way",
    "phone": "16503600708",
    "prices": 
      {
        "Cafe Latte": 4.75,
        "Flat White": 4.75,
        "Cappucino": 3.85,
        "Single Espresso": 2.05,
        "Double Espresso": 3.75,
        "Americano": 3.75,
        "Cortado": 4.55,
        "Tea": 3.65,
        "Choc Mudcake": 6.40,
        "Choc Mousse": 8.20,
        "Affogato": 14.80,
        "Tiramisu": 11.40,
        "Blueberry Muffin": 4.05,
        "Chocolate Chip Muffin": 4.05,
        "Muffin Of The Day": 4.55
      }
    }
  }

I want this in another file in the folder, because I want things to look neat

  main.js

I've tried this:

  var helper = require('./helper');

I simply want main.js to know what shopInfo is

Assuming you're talking about a server side node.js program, you can put it in another module file and then export it by assigning to modules.exports .

In helper.js:

 var localShopInfo = {
     "shopName": "The Coffee Connection",
     "address": "123 Lakeside Way",
     "phone": "16503600708",
     "prices": {
         "Cafe Latte": 4.75,
         "Flat White": 4.75,
         "Cappucino": 3.85,
         "Single Espresso": 2.05,
         "Double Espresso": 3.75,
         "Americano": 3.75,
         "Cortado": 4.55,
         "Tea": 3.65,
         "Choc Mudcake": 6.40,
         "Choc Mousse": 8.20,
         "Affogato": 14.80,
         "Tiramisu": 11.40,
         "Blueberry Muffin": 4.05,
         "Chocolate Chip Muffin": 4.05,
         "Muffin Of The Day": 4.55
     }
 };

// assign to module.exports to make it available to other modules
module.exports = localShopInfo;

Then, in main.js:

var shopInfo = require('./helper');

You are now free to use shopInfo anywhere in main.js.


The require() loader returns the value of module.exports in the module that it loaded. You then assign that to whatever variable in your current module that you want it to be called.


Note: you had an extra closing brace in your shopInfo declaration too.

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