javascript - 导出变量时如何解决“语法错误:导出声明只能出现在模块的顶层”?
问题描述
我是编程新手,目前正在用 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 };
};
解决方案
考虑反转您的控制流。与其尝试导出尚不存在的变量,不如从另一个文件导入一个函数,然后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);
};
推荐阅读
- html - Flexbox,在不使用媒体查询的情况下填充宽度
- elasticsearch - ElasticSearch NEST DSL 查询 跨字段查询
- r - 我无法将库加载到 Rstudio
- python - 如何将 df.value_counts 与 csv 文件一起使用?
- azure - 在 Azure DevOps 中为 Nuget 部署安装 Mono
- javascript - 获取js文件目录
- php - 数据库中的电子邮件列被加密时无法发送密码重置电子邮件(Laravel 8)
- vba - 自动将数据更新/插入到另一个 MS Access 表中
- python - 如何从 Tkinter 中的类中检索条目小部件文本
- iis - 在 IIS 8.5 中隐藏 http 标头响应中的一些信息