js模块导入排序和执行问题

js module import ordering and execute problem

我正在使用 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,然后在答:

// 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