我是编程新手,目前正在用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 };
};
答案 0 :(得分:0)
导出时,必须从要导出的源文件的“作用域”中进行操作,而不是从当前的功能(即,从exports()
函数内部)进行操作。
一个简单的解决方法是修改JavaScript.js
模块,以使要导出(并导入到另一个模块中)的变量在声明时直接导出到{{1}的顶层}模块:
JavaScript.js
JavaScript.js
OtherModule
// Start of JavaScript.js file - do not nest exports inside of any function, etc
export const cakeChoicePricing = // Some value or function
export const cakeTypeResultPricing = // Some value or function
export const cupcakeChoicePricing = // ..
export const cupcakeTypeResultPricing = // ..
答案 1 :(得分:0)
考虑反转控制流。与其尝试导出尚不存在的变量,不如从另一个文件导入一个函数,然后在需要时使用<div class="topnav" id="myTopnav">
<a href="#home" class="active">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
<div class="dropdown">
<button class="dropbtn">Dropdown
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
<a href="#about">About</a>
<a href="#" style="font-size:15px;" class="icon" data-action="toggleMenu">☰</a>
</div>
<div style="padding-left:16px">
<h2>Responsive Topnav with Dropdown</h2>
<p>Resize the browser window to see how it works.</p>
<p>Hover over the dropdown button to open the dropdown menu.</p>
</div>
等参数调用该函数。例如:
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);
函数(其他文件导出该函数)来处理具有prices属性的对象,例如
displayPrices