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
});
I think the best way to structure this would be to make your initializeSdk the explicit entry point, while it imports other needed modules that consume it. For example:
// index.js
import createApp from '@shopify/app-bridge';
import { somethingThatUsesApp } from './somethingThatUsesApp';
document.addEventListener('DOMContentLoaded', () => {
const data = document.getElementById('shopify-app-init').dataset;
const app = createApp({
apiKey: data.apiKey,
shopOrigin: data.shopOrigin,
forceRedirect: true
});
somethingThatUsesApp(app);
});
// somethingThatUsesApp.js
export const somethingThatUsesApp = (app) => {
console.log('app is ' + app)
};
IMO, having a single entry point, while other modules export functions only (which might take runtime-dependencies as arguments) is one of the better ways to organize things.
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