且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用类型模块访问脚本标记中定义的变量?

更新时间:2022-06-11 22:46:48

首先,您应该使用 import 适用于html文件.但是,对于另一个js文件中的单独js文件,您可以仅使用import {life} from 'path/to/file'加载变量.如果它嵌入在html中,并且您在同一页面中使用脚本,则不需要export,并且只需使用变量life即可访问life.实际上,type="module"实际上阻止访问script标记中定义的变量.如果要访问同一页面上的变量,则应将其删除.页面上的开发者控制台也是如此.

First of all, you should be using export in separate js files and not embedded in an html file. I'm not sure if import works on html files. However, for a separate js file in another js file you can just use import {life} from 'path/to/file' to load the variables. If it's embedded in html and you use scripts in the same page, you do not need the export and you can access life simply by using the variable life. In fact, the type="module" actually prevents variables defined in the script tag from being accessed. If you want to access the variables on the same page then you should remove it. The same applies for the developer console on the page.