简体   繁体   English

Javascript,要求var

[英]Javascript, require var

 helper.js

I usually program in Ruby. 我通常用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 我只是想让main.js知道shopInfo是什么

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 . 假设您正在谈论服务器端的node.js程序,则可以将其放在另一个模块文件中,然后通过分配给modules.exports导出它。

In helper.js: 在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: 然后,在main.js中:

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

You are now free to use shopInfo anywhere in main.js. 现在,您可以在main.js中的任意位置自由使用shopInfo


The require() loader returns the value of module.exports in the module that it loaded. require()加载程序在其加载的模块中返回module.exports的值。 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. 注意: shopInfo声明中也有一个额外的结束括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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