Reputation: 1397
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.
I already had to add expose-loader to my webpack.config.js to get jquery to work as per this issue:
Upvotes: 2
Views: 1613
Reputation: 1397
I couldn't figure out how to get ES6 syntax to work in the file, kept running into this error:
Here's a workaround based on this related question
Upvotes: 0
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