I'm doing a little testing setup for typescript. My main focus is to bundle all .ts modules into a single .js file that can be client-side referenced in a simple index.html. This is my test module:
// index.ts
import { Example } from './example'
class x {
example(): void {
console.log(Example)
}
}
let test = new x()
test.example()
// example.ts
export const Example : string = 'Example Message'
I compile everything into a bundle.js file using Webpack 5 and ts-loader. Then, I created an .html file to test the created class. There the test.example() inside index.ts (and then bundle.js) executed correctly, but the second one, inside the <script/> reports Uncaught ReferenceError: x is not defined.
<!-- index.html -->
<html>
<script src="../dist/js/bundle.js"></script>
<script>
// Uncaught ReferenceError: x is not defined
let test = new x()
test.example()
</script>
</html>
How can I reference my class x from the second <script/>?
CodePudding user response:
How can I reference my class x from the second
<script/>?
You can't. At least not without modifying your source code structure.
A bundler puts all your executable code into the bundle. That includes your dependencies, and your application code. And all that is only really designed to work from within that bundle via the import and export keywords.
The bundler manages those import/exports in a way that doesn't pollute the global scope. But it does require that you stay within that bundle.
However, you seem to want your bundle to make some values available in that global scope. And to do that, you must be explicit about it.
class x {
example(): void {
console.log(Example)
}
}
// Add `x` to the browser's global scope.
window.x = x
Now from some other <script> tag new x() should work as you expect.
