Search code examples
javascripttypescriptwebpackwebpack-4

Expose a function from a webpack bundle


I'm trying to expose a function to a webpage, that can be called externally, or on window.load, or at anypoint.

DoThing.ts

import * as lib from "libs";

export default function DoAThingFunc():void{
    console.log('Do a thing)'
}

This is then imported thing ExposeDoThing.js

import DoAThingFunc from './DoThing'
window.exposeFunc = DoAThing
window.exposeFunc():

webpack 4 bundle

     entry: {
            main: './src/MainEntry.tsx',
            popupcallback: './src/ExposeDoThing.js'
        },
        output: {
            path: path.join(__dirname, outputDir + "/js"),
            filename: '[name].js',
            publicPath: "/js/",
            library:'pclGlobal'
        },

MyPage.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pop up</title>
</head>

<body>
    <script src="/js/vendor-main.js" type="text/javascript"></script>
    <script src="/js/popupcallback.js" type="text/javascript"></script>
</body>

</html>

Nothing is being called, pclGlobal is undefined even though:

var pclGlobal=(window.webpackJsonppclGlobal=window.webpackJsonppclGloba...

is present in the output. And nothing is being called from the functions. I just want the function DoAThingFunc() to fire when the script has loaded, what am I missing?


Solution

  • I noticed the vendor-main.js in my quoyted html example, except we don't have one in the weback entry and yet there is file output... It looks like we used to have a vendors bundle, and then stopped but left the following the webpack.config.js

                runtimeChunk: {
                    name: entrypoint => `vendor-${entrypoint.name}`
                }
    

    This has a weird effect. If your entry is not called main, then it wouldn't any execute anyexport default functions.