Javascript,需要变量

Javascript, require var

 helper.js

我通常在 Ruby 编程。我想获取此信息:

 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
      }
    }
  }

我想把它放在文件夹的另一个文件中,因为我想让东西看起来整洁

  main.js

我试过这个:

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

我只是想 main.js 知道 shopInfo 是什么

假设你在谈论服务器端 node.js 程序,你可以将它放在另一个模块文件中,然后通过分配给 modules.exports.

来导出它

在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;

然后,在main.js中:

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

您现在可以在 main.js 的任何地方免费使用 shopInfo


require() 加载程序 returns 它加载的模块中 module.exports 的值。然后,您可以将其分配给当前模块中您希望调用它的任何变量。


注意:您的 shopInfo 声明中也有一个额外的右大括号。