sshevlyagin
sshevlyagin

Reputation: 1397

Uncaught ReferenceError - how to access function bundled by webpack

I'm using https://github.com/sloria/cookiecutter-flask for a project and I'm trying to add a javascript function to a js file that's bundled by webpack and access it from the html. I think I'm missing something basic.

Source files for background:

I'm adding the following code to plugins.js:

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

And trying to call it from an html document to test as follows

<script type="text/javascript">
    foo();
</script>

I can see that my function got bundled, but I can't access it. output code

And here's the error I get: Error in browser

I already had to add expose-loader to my webpack.config.js to get jquery to work as per this issue: enter image description here

Upvotes: 2

Views: 1613

Answers (2)

sshevlyagin
sshevlyagin

Reputation: 1397

I couldn't figure out how to get ES6 syntax to work in the file, kept running into this error: error

Here's a workaround based on this related question enter image description here

Upvotes: 0

Alexander Nied
Alexander Nied

Reputation: 13678

In my experiene, when I am using Webpack, I am bundling code into modules, which encapsulates them to that module's scope. Code that I want to be available outside of the module I explicitly export, and then import or require it into the new scope where I want to access it.

It sounds like you are instead wishing for some of your code to be accessible in the global scope, to access it directly from your markup. To do this in the browser, your best bet is to attach it directly to the Window object. Probably first checking to make sure that you aren't overwriting something already at that namespace:

function foo() {
    console.log('bar!');
}

if (!Window.foo) {
    Window.foo = foo;
} else {
    console.warn('Foo is already assigned!');
}

That said, I would recommend you avoid developing in this manner-- polluting the global namespace is usually not a great pattern, and leads to a lot of potential conflict. If you must work in this manner, at least assign an object to a namespace attached to Window where you can put your applications functionality without risking conflicting with other Window properties:

Window.myApp = {
    foo: function () {
        console.log('bar!');
    }
}

Window.myApp.printGreeting = function () {
    console.log('Hello!');
}

// ...etc

Upvotes: 2

Related Questions