4

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
  });

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it works - how do I use somethingThatUsesApp in a .js file that isn't index.js (without running into the original DomContentLoaded issue)?
Have index.js import the other module instead, and then that other module can import somethingThatUsesApp. index: somethingElse(app). somethingElse: somethingThatUsesApp(app)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.