怎么解决语法错误:导出变量时,导出声明可能只出现在模块的顶层?
原学程将引见若何处理语法毛病:导出变质时,导作声明能够只涌现在模块的顶层?的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。
成绩描写
我是编程老手,今朝正在用HTML、CSS以及JavaScript建立1个项目。我想将变质从我的1个内部JavaScript文件导出到另外一个文件。但是,当我测验考试它时,从Mozilla Firefox的掌握台获得1个毛病。毛病是:"语法毛病:导作声明能够只涌现在模块的顶层"。
我测验考试在代码的开首、开头以及函数外部(我愿望从中导出)停止导出。我在网上找过了,但是我仿佛找没有就任何谜底,只要导进的谜底。
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 };
};
推举谜底
斟酌倒置掌握流。与其测验考试导出尚没有存留的变质,没有如从另外一个文件导进1个函数,而后在须要时应用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);
};
佳了闭于怎样处理语法毛病:导出变质时,导作声明能够只涌现在模块的顶层?的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。