3

I'm using Vue and recently got a problem.

if I have two file, fileA and fileB and in fileB I write console.log('file B test')

when I do

console.log('file A test') 
import B from '@/app/fileB'

-> the devTool shows file B's console.log first  

so what's might be the problem here? the import ordering ? does it guaranteed to import and execute from top to bottom ? If someone knows anything about import or execute ordering, thanks first!!

1 Answer 1

3

Import statements are always hoisted to the very top of a module. A module that contains

// some non-import code
import foo from 'foo';
// some more non-import code 2
import bar from 'bar';
// some more non-import code 3

will run as if all the imports were at the very top:

import foo from 'foo';
import bar from 'bar';

// some non-import code
// some more non-import code 2
// some more non-import code 3

For what it sounds like you want to do, you could have B have an init method or something that you call to make it do its stuff:

import B from '@/app/fileB'
console.log('file A test')
B.init();

Another option I prefer is to always import and export functions - you could have a makeB module instead of B, and then call it in 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
Sign up to request clarification or add additional context in comments.

2 Comments

hi @CertainPerformance, thanks for your reply. so you said "Import statements are always hoisted to the very top" what if i have multiple import file, and inside each file also have multiple import ? is all the import been hoisted to the top first ? cuz now I'm maintaining a project and facing some ordering problem and trying to figure out, but the code execute ordering is different from my thought. :(
Yes, all the imports for all files will be hoisted to the top - every file will be loaded before any of the JavaScript proper actually runs. My solution of choice for this problem is to always export functions, and to avoid side-effects on the top level of modules. stackoverflow.com/a/52827581 stackoverflow.com/a/59998121 stackoverflow.com/a/63529657

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.