如何解决语法错误:导出变量时,导出声明可能只出现在模块的顶层?

2022-08-02 00:00:00 export javascript

我是编程新手,目前正在用HTML、CSS和JavaScript构建一个项目。我想将变量从我的一个外部JavaScript文件导出到另一个文件。然而,当我尝试它时,从Mozilla Firefox的控制台得到一个错误。错误是:"语法错误:导出声明可能只出现在模块的顶层"。

我尝试在代码的开头、结尾和函数内部(我希望从中导出)进行导出。我在网上找过了,但我似乎找不到任何答案,只有导入的答案。

function exports() {
    export { cakeChoicePricing, cakeTypeResultPricing };
    export { cupcakeChoicePricing, cupcakeTypeResultPricing };
};

正在导入以下内容:

import { cakeChoicePricing, cakeTypeResultPricing } from './JavaScript.js';
import { cupcakeChoicePricing, cupcakeTypeResultPricing } from './JavaScript.js';

感谢您提供的帮助!

更新(以下是我的更多代码):

let cakeChoicePricing;
let cupcakeChoicePricing;
function dessertChoiceCake() {
        cakeElement.setAttribute('class', 'disabled'); //Set cake button to unclickable
        cakeChoicePricing = 'Cake';
        cupcakeChoicePricing = 'Cake';
}
let exportCake = document.getElementById("cakeReviewButton");
let exportCupcake = document.getElementById("cupcakeReviewButton");

exportCake.addEventListener("click", exports);
exportCupcake.addEventListener("click", exports);

function exports() {
    export { cakeChoicePricing, cakeTypeResultPricing };
    export { cupcakeChoicePricing, cupcakeTypeResultPricing };
};

解决方案

考虑颠倒控制流。与其尝试导出尚不存在的变量,不如从另一个文件导入一个函数,然后在需要时使用cakeChoicePricing等参数调用该函数。例如:

import displayPrices from './prices';

const prices = {};

// when you need to, assign to properties of the prices object:

function dessertChoiceCake() {
  cakeElement.setAttribute('class', 'disabled'); //Set cake button to unclickable
  prices.cakeChoicePricing = 'Cake';
  prices.cupcakeChoicePricing = 'Cake';
}

const callDisplayPrices = () => {
  displayPrices(prices);
};

exportCake.addEventListener("click", callDisplayPrices);
exportCupcake.addEventListener("click", callDisplayPrices);

并让displayPrices函数(其他文件导出)处理具有价格属性的对象,例如

export default (prices) => {
  console.log('cakeChoicePricing:', prices.cakeChoicePricing);
};

相关文章