Ryan Dorn
Ryan Dorn

Reputation: 807

Expose Functions Using Webpack & Then Call Them From an Inline Script

I'm working on getting a bunch of legacy inline scripts cleaned up.

My question is: How do I call a function from an inline script that is compiled in WebPack.

Currently, I get one of two errors:

Error 1:

"Uncaught TypeError: derpFunc is not a function"

Error 2:

Uncaught Error: [exposes-loader] The "derpFunc" value exists in the global scope, it may not be safe to overwrite it, use the "override" option

derpFunc.js

function derpFunc(){
    console.log('derp');
}
window.appCalendar  = appCalendar; // If I comment this out, I get Error #2
export { appCalendar }; // If I comment this out, I get Error #1

wepback.config.js

// Expose Legacy functions for use outside Webpack build
{
    test: require.resolve('./derpFunc.js'),
    use: [
        {
        loader: 'expose-loader',
        options: {
            exposes: [
                'derpFunc'
            ],
            override: true
        }
        }
    ]
},

In other words, my issue is: A) If I don't add my function to the global scope, then it does exist 2) If I do add it to the global scope, then I get a global scope error

Upvotes: 0

Views: 832

Answers (1)

Ryan Dorn
Ryan Dorn

Reputation: 807

Well, in typical fashion, the solution presented itself a few minutes after posting here. ¯\_(ツ)_/¯

Wrapping my function in a namespace seems to be working.

derpFunc.js

const myNamespace = {
  derpFunc: function() {
    console.log('derp');
  }
};
window.myNamespace = myNamespace;
export { myNamespace };

inline script

myNamespace.derpFunc();

Upvotes: -1

Related Questions