DEV Community

loading...
Cover image for Exposing your Webpack bundle to the DOM

Exposing your Webpack bundle to the DOM

grant_bartlett profile image Grant ・2 min read

Quite recently the team I was working with needed a way to interact with our web application with some server side code. It was being bundled by Webpack and thus it wasn't exposed to the DOM in a way that was accessible with the current configuration.

Looking at the Webpack documentation, I discovered Authoring Libraries.
Note: I recommend reading through this documentation, especially if you're planning to write a library of your own and are including existing libraries within your application, you'll want to pay special attention to externals and peerDependency.

Basic example

If you don't already have an existing Webpack project to try this with, I've included a basic example on GitHub to clone off. It's an example of a Logger class being called from the DOM.

Step 1

In your webpack.config.js set the entry point of your app. In this example I'm using a Logger class.

        entry: {
            app: [
                "./src/Logger.ts"
            ]
        },

My Logger.ts contains:

export class Logger
{
    constructor()
    {
    }

    public log(message: string): void
    {
        console.log(message);
    }
}

Step 2

Now in your webpack.config.js under the output object, fill in the library and libraryTarget properties.

The library name in this example I'm calling "MyAwesomeLibrary" and the libraryTarget as "var".

        output: {
            filename: "js/my-awesome-library.js",
            path: path.resolve(__dirname, "dist"),
            library: "MyAwesomeLibrary",
            libraryTarget: "var"
        },

From the docs:
You can expose the library in the following ways:

  • Variable: as a global variable made available by a script tag (libraryTarget:'var').

  • This: available through the this object (libraryTarget:'this').
    Window: available through the window object, in the browser (libraryTarget:'window').

  • UMD: available after AMD or CommonJS require (libraryTarget:'umd').

Step 2

Once our bundle has recompiled we are able to access our MyAwesomeLibrary within the DOM. Try it out by typing into to your browser console "MyAwesomeLibrary".

Console showing MyAwesomeLibrary object

Step 3

Try it out within the html of your page now, calling a function within our Logger class.

    <script>
        const logger = new MyAwesomeLibrary.Logger()
        logger.log("My message");
    </script>

Refresh the page and you should see "My Message" logged out to the console.
Console showing My Message output

That's it

GitHub example can be found here.

Discussion (0)

pic
Editor guide