简体   繁体   中英

Webpack 2: Expose variable to global context, and use it in same project

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM