I'm new to ES6 and importing/exporting modules, and I am confused as to how to achieve what I want. I have one .js file that initializes an SDK and must wait for the dom content to load first.
I have other smaller .js files where I want to write methods that reference/import the app object from the first file. However, I can't get it to work without wrapping everything in DOMContentLoaded within those smaller files as well.
I imagine there's a better way, and I also recognize my overall approach here might be off - I'm relatively new to Javascript and in general I'm trying to figure out the best way to break things into multiple .js files to achieve cleaner code. Thank you.
// initializeSdk.js
import createApp from '@shopify/app-bridge';
export {app} // i want to export this object so other .js files can use it
var app;
document.addEventListener('DOMContentLoaded', () => {
var data = document.getElementById('shopify-app-init').dataset;
app = createApp({
apiKey: data.apiKey,
shopOrigin: data.shopOrigin,
forceRedirect: true
});
return app;
});
// otherFile.js
import {app} from './initializeSdk.js';
console.log('app is ' + app) // returns undefined
document.addEventListener('DOMContentLoaded', () => {
console.log('app after waiting is ' + app) // this returns app object
});