3

Fairly new to JS modules of any kind. I have a simple vanilla JS script that is intended to be loaded into an html document via the script tag. Basically...

// invoke main function when DOM is ready
document.addEventListener("DOMContentLoaded", function() {
    MainFunction();
});

var MainFunction = function() {
    // check for specific DOM nodes upon invocation...
}

Works great. But I'd like to also be able to make MainFunction available as a module export so I can import it into a webpack bundle like:

import MainFunction from 'myclassicscript';

And then I can invoke it as necessary in the main bundle with:

MainFunction();

How the same script can be used both ways. I can't seem to find any info on how to do it, but I might have totally the wrong idea.

Something like...?

// check if this is a browser environment...
if (typeof window !== 'undefined') {

    // invoke main function when DOM is ready
    document.addEventListener("DOMContentLoaded", function() {
        MainFunction();
    });

}

var MainFunction = function() {
    // check for specific DOM nodes upon invocation...
}

// ???
export default MainFunction;
3
  • If I'm not wrong you can only add a javascript file through script tag, since import is an ES6 spec which hasn't been implemented yet in any browser Commented May 24, 2018 at 15:25
  • I'm using webpack to do the imports Commented May 24, 2018 at 15:26
  • @GustavoTopete It has been, for over a year now Commented May 24, 2018 at 15:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.