我想在其他js文件中使用main.js文件中的变量,我尝试了一切(导出模块、声明全局变量(,但都不起作用,我必须这样做,因为其他js文档在很大程度上依赖于main.js文件中的变量。
有其他方法吗?如果有,请启发我。
既然您已经说过您正在编写要在web浏览器中执行的JavaScript代码,下面是您的main.js
文件的样子(包含变量importantVariable(:
const importantVariable = 10;
接下来,我们有另一个JavaScript文件other.js
(使用变量importantVariable(:
console.log(importantVariable);
在愿意使用脚本的HTML文档中,在other.js
文件之前包含main.js
。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="main.js"></script>
<script src="other.js"></script>
</body>
</html>
你应该得到";10〃;在控制台中,这表明一个文件与其他文件的变量共享成功。
说明:全局作用域中的变量在声明后加载的所有脚本都应该可以访问。
我们可以在浏览器中使用es模块。
index.html
<!DOCTYPE html>
<html>
<body>
<script type="module" src="./main.js"
</body>
</html
main.js
import { message } from "./other.js";
console.log(message)
其他.js
export const message = "haha"
注意:
由于CORS policy
,直接打开index.html
将引发错误。
...has been blocked by CORS policy...
因此,您需要在服务器中部署它们。
您是否尝试将其导入接收JavaScript文件?这有时是必要的,以及导出它
在index.js中:export someVariable
在其他FIle.js:import { someVariable } from './index'
中