0

I'm trying to expose an object to the global context using Webpack 2 and TypeScript. This variable needs to be globally accessible because it's going to receive commands and attributes from an external script, so it cannot be existing in its enclosed context.

I saw this question, which taught me how to output one bundle via the output.library configuration.

Here is my webpack.config file:

entry:{
    fluxCapacitor: "./ts/main/fluxCapacitor.ts",
    control: "./ts/control/index.ts"
},

output:{
    path: __dirname + "/js",
    filename: "[name].js",
    library: "[name]",
    libraryTarget: "var"
},

fluxCapacitor.ts file:

export default class Core{
    constructor(){
        console.log("Need more jiggawatts");
    }
}

control/index.ts file:

var myFlux = new (<any>window).fluxCapacitor.default();

The problem I have now is that the fluxCapacitor class is available globally, but the instance myFlux is not. Now myFlux is trapped in the control context, and I cannot reach it using the browser console.

I also tried adding the variable to the window object, but TypeScript simply won't let me:

window.myFlux = new (<any>window).fluxCapacitor.default();
// property 'myFlux' does not exist on type 'Window'

Question:

What is the easiest/simplest way to expose a variable to the global scope, out of Webpack's bundled context?

Community
  • 1
  • 1
M -
  • 26,908
  • 11
  • 49
  • 81

1 Answers1

1

For a class instance, just do the same thing you're doing for the class -- export it:

myFlux.ts

import fluxCapacitor from './fluxCapacitor';

export default fluxCapacitor.default();

webpack.config.js

entry:{
    ...
    myFlux: "./ts/main/myFlux.ts",
    ...
},

and myFlux will end up on the window object.

m1kael
  • 2,801
  • 1
  • 15
  • 14