In ts/app.ts, there is:
function foo() {
console.log('Hello Word');
}
It compiles successfully with Webpack into bundle.js and is loaded with:
<script src="dist/bundle.js"></script>
How to execute foo from my browser console?
> foo()
Uncaught ReferenceError: foo is not defined
As you have it, you can't access it globally. But if you want you can do
function foo() {
console.log('Hello Word');
}
(window as any).foo = foo;
Then it should be available on the window object (which means you can access it either as window.foo() or just foo() since the window object is the global object.
Variables and methods like foo are private to the module (ie. file) they're in by default. You can export them like this:
export function foo() {
console.log('Hello Word');
}
And that means you can import them from other modules, i.e.
import {foo} from "foo";
foo();
However the browser itself doesn't understand that import and export syntax (*) so they're still not global. It's webpack that understands that syntax and stitches them all together into a form that the browser can use (in your "dist/bundle.js" file). Have a look at that file and you'll see the bootstrap code that webpack has inserted.
(*) Edit: Browsers are starting to support modules:
Essentially, nothing's global, but that's a good thing because otherwise they could conflict with each other. i.e. it wouldn't be modular.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With