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!!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With