如何在ES6中访问和使用导入功能

时间:2018-08-23 15:04:17

标签: javascript import ecmascript-6 export es6-modules

我无法访问导入的labelsForCountryCode函数。当将“ US”传递给此函数时,我期望返回US对象。我是ES6的新手,不确定自己在做什么错。感谢任何帮助!

billing-address-labels-lookup.js

export default function billingAddressLabelsLookup() {

const labelsLookup = {
  'US': {
    addressLineOne: 'Street/Address',
    city: 'City',
    provinceCode: 'State',
    postalCode: 'Zip Code'
  },
  'CA': {
    addressLineOne: 'Street/Address',
    city: 'City',
    provinceCode: 'Province',
    postalCode: 'Postal Code'
  }
};

return {
  labelsForCountryCode(countryCode) {
    return labelsLookup[countryCode];
  }
};

};

test.js

 import billingAddressLabelsLookup from '../utils/billing-address-labels-lookup.js';

 var labels = billingAddressLabelsLookup.labelsForCountryCode('US');

1 个答案:

答案 0 :(得分:2)

只需替换:

var labels = billingAddressLabelsLookup.labelsForCountryCode('US');

具有:

var labels = billingAddressLabelsLookup().labelsForCountryCode('US');
                                       ^^------ function call

否则,您尝试访问功能引用的属性,而您需要访问功能的结果

关于进出口,请具体看一下本章:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export#Using_the_default_export