我有一个脚本,可以导入很多不同的文件,就像这样:
<script type="module">
import * as A from '...';
import * as B from '...';
import * as C from '...';
我有自己的模块,我也想导入并在其中使用A,B,C。 目前,我在“ myfile.js”中有此代码段:
var init = (function () {
console.log(A,B,C);
})();
export { init };
如果我在所有其他对象之后添加导入,则:
<script type="module">
import * as A from '...';
import * as B from '...';
import * as C from '...';
import * as my from 'myfile.js';
我收到未定义A,B,C的错误。我该如何运作?
编辑以澄清:
A,B,C在导入语句之后就存在,所以我可以像这样访问它们:
import * as A from ....
console.log(A);
import * as B from ...
console.log(B);
我还可以从模块内部访问全局变量,例如:
import * as A from ....
console.log(A);
import * as B from ...
console.log(B);
import * as my from 'myfile.js'
myfile.js:
var init = (function (t) {
console.log(t);
})(window.innerWidth);
export { init };
这将打印窗口宽度。
我正在寻找类似的功能来工作:
var init = (function (t) {
console.log(t);
})(A);
export { init };
回调函数非常类似于导入我的模块,然后调用一个函数并将A作为参数传递给它,我可以在没有回调的情况下做到这一点。
答案 0 :(得分:0)
不能。完全实现模块解析是为了不提倡全局范围,并避免程序员问“此变量是否存在?”。 因此,您可以使用旧式JavaScript,从而禁用模块系统。不要将“ myfile”用作模块,而应将其用作全局导入:
<script src="myfile.js"></script>
如果使用的是构建阶段,这很危险。
或者更好的是,您可以避免任何对A,B和C的明确引用,因为您不知道它们那时是否存在。您可以使用回调:
var init = function (cb) {
cb();
};
// use:
import {init} from ...
init(() => console.log(A,B,C));
PS。您正在混合新旧语法
答案 1 :(得分:0)
您正在将它们导出为组件,我想使用{}大括号进行初始化。如果要将它们导出为组件,则必须在要导出的模块旁边使用default关键字。尝试导出默认值{init};
答案 2 :(得分:0)
在JavaScript中,作用域由代码块,函数,模块创建。 因此,无法在模块外部访问模块变量(除非使用export显式导出)。
如果要在myFile.js
中导入A,B,C,则应使用它们。
所以myFile.js
将是:
import * as A from '...';
import * as B from '...';
import * as C from '...';
var init = (function () {
console.log(A,B,C);
})();
export { init };
的一些有用的文章