ChildishGiant
ChildishGiant

Reputation: 340

Functions not defined but can be used in console (Webpack)

When using webpack I'm having issues with functions

Functions defined like this aren't available at all:

function foo() {
    console.log("bar")
}

When I define a function like this it works in the console:

window.foo = function() {
    console.log("bar")
}

But it doesn't work when called from code like

window.test = function () {
    foo()
};

<button onclick="test()">

Upvotes: 1

Views: 875

Answers (1)

yagiro
yagiro

Reputation: 777

This is expected behavior. Webpack creates a separate scope for each module. The proper way to declare variables/functions/etc on the global context is by using the window object.

Keep in mind that you don't need the global context (window) in order to share functions between your modules. You can expose functions from a module by using the export statement, and use them on other modules in your project.

Upvotes: 1

Related Questions