首页 > 解决方案 > 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  

那么这里可能是什么问题?进口订货?它保证从上到下导入和执行吗?如果有人知道有关导入或执行订购的任何信息,请先感谢!

标签: javascriptimportmodule

解决方案


导入语句总是被提升到模块的最顶部。一个模块包含

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

推荐阅读