首页 > 解决方案 > 导出变量时如何解决“语法错误:导出声明​​只能出现在模块的顶层”?

问题描述

我是编程新手,目前正在用 HTML、CSS 和 JavaScript 构建一个项目。我想将变量从我的一个外部 JavaScript 文件导出到另一个。但是,我在尝试 Mozilla Firefox 时从控制台收到错误消息。错误是:“SyntaxError:导出声明​​只能出现在模块的顶层”。

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

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

标签: javascriptexport

解决方案


考虑反转您的控制流。与其尝试导出尚不存在的变量,不如从另一个文件导入一个函数,然后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);
};

推荐阅读