我正在尝试从另一个文件访问var一个文件。这是我所拥有的:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id="btn">Global</button>
<script src="/test.js"></script>
<script src="/testpass.js"></script>
</body>
</html>
test.js:
export var globalVariable = {
output: "test this"
};
testpass.js:
import { globalVariable } from './test.js'
document.getElementById("btn").addEventListener("click", function(){
alert(globalVariable.output);
});
什么都没发生。我也尝试过
var globalVariable = {
output: "test this"
};
,然后如以下答案所示,仅从另一个文件访问它: Call variables from one javascript file to another,但无效。也尝试按照以下答案中的说明进行导出:Can I access variables from another file?,但没有成功。我正在使用sublime文本和vue.js,但对它们两者均无效。
此外,如果我执行以下操作:
import { globalVariable } from '.test.js'
document.getElementById("btn").addEventListener("click", function(){
alert("Not printing the globalVariable here");
});
当在HTML文件中调用时,整个javascript文件似乎都无法正常运行。
答案 0 :(得分:7)
您应该从Web控制台中的浏览器的JavaScript引擎中得到一个错误。要使用import
和export
,您必须将代码视为模块。您的script
标签没有,它们将代码视为 script 。要将testpass.js
视为模块,必须使用type="module"
:
<script src="/testpass.js" type="module"></script>
无需列出test.js
,testpass.js
将加载它。所以:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id="btn">Global</button>
<script src="/testpass.js" type="module"></script>
</body>
</html>
遗憾的是,我们无法在SO的堆栈片段中显示模块,但是如果您进行了这些更改,this codesandbox example就是您的最终选择(除了我将src="/testpass.js"
更改为src="./testpass.js"
以外)
请注意,globalVariable
不是全局变量(Good Thing™)。它是test.js
中导出的局部变量。任何其他模块都可以导入它,但是它不是全局的。