如何解决语法错误:导出变量时,导出声明可能只出现在模块的顶层? [英] How to resolve 'SyntaxError: export declarations may only appear at top level of a module' when exporting variables?

查看:0
本文介绍了如何解决语法错误:导出变量时,导出声明可能只出现在模块的顶层?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,目前正在用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);
};

这篇关于如何解决语法错误:导出变量时,导出声明可能只出现在模块的顶层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆