javascript - js模块导入排序和执行问题
问题描述
我正在使用 Vue,最近遇到了问题。
如果我有两个文件,fileA 和 fileB,并且在 fileB 中我写console.log('file B test')
当我做
console.log('file A test')
import B from '@/app/fileB'
-> the devTool shows file B's console.log first
那么这里可能是什么问题?进口订货?它保证从上到下导入和执行吗?如果有人知道有关导入或执行订购的任何信息,请先感谢!
解决方案
导入语句总是被提升到模块的最顶部。一个模块包含
// some non-import code
import foo from 'foo';
// some more non-import code 2
import bar from 'bar';
// some more non-import code 3
将像所有导入都在最顶部一样运行:
import foo from 'foo';
import bar from 'bar';
// some non-import code
// some more non-import code 2
// some more non-import code 3
对于听起来你想做的事情,你可以让 B 有一个init
方法或你调用的东西来让它做它的事情:
import B from '@/app/fileB'
console.log('file A test')
B.init();
我更喜欢的另一个选择是始终导入和导出函数- 你可以有一个makeB
模块而不是B
,然后在 A 中调用它:
// b
export const makeB = () => {
const b = {};
console.log('creating B now');
// other stuff
return b;
};
// a
import { makeB } from './makeB';
console.log('file A test');
const b = makeB();
// do stuff with b
推荐阅读
- django - 如何更改在普通 django 中工作的此功能以使其与序列化程序一起使用?
- java - org.hibernate.exception.GenericJDBCException:无法执行结果的顺序读取(转发)
- reactjs - 如何正确测试我的 App 组件以验证路由是否呈现正确的组件
- firebase - Firebase 和邮递员 | 为 Google Identity OAuth 2.0 令牌生成 JWT
- swift - 完成处理程序中的 Swift 泛型
- lua - lua 5.4 __close 和 collectgarbage 导致崩溃
- elasticsearch - 对于弹性搜索索引,如何获取数组字段长度大于0的文档?
- java - 为什么 Android IAP 初始化但无法正常工作?
- python - 在 jupyter notebook 中使用 matplotlib 绘图未正确显示
- java - 数据保存到数据库期间会话过期