1

I have a webpack-bundled TypeScript file which exports a function I need to use from global, e.g.:

// bundled.ts
import * as Excel from 'exceljs';
import { saveAs } from 'file-saver';

declare const $find: any;

export function configExport() {
    $('#ExportToExcelBtn').click( async () => {
        ...
        let dataItems = $find('ViewGrid').get_masterTableView().get_dataItems();
        ...
    });
}
// notBundled.js
configExport(); // does not exist in global window object

I must not be reading the docs correctly or something, but I am having trouble getting the configExport function exposed/exported/provided/whatever to window. I have looked into export-loader, expose-loader, and ProvidePlugin, but I am not getting a clear sense of what I should do here.

So far I have tried something like this in my webpack.config.js:

    module: {
        rules: [
            {
                test: require.resolve("./Module/js/dist/bundled.js"),
                use: [{
                    loader: "expose-loader",
                    options: "bundledModuleCode",
                }]
            },

but neither configExport nor bundledModuleCode appear in window like I would want.

  1. Is this use case even supported?
  2. How do I go about it?
Bondolin
  • 2,793
  • 7
  • 34
  • 62
  • I see no place, in the code you've provided, where `configExport` is ever imported. If you do not import it, tree-shaking will completely eliminated it from your bundle. If you want the function to be global (which I wouldn't want it to be, since you can always import it everywhere it is needed), you'll have to attach that function to a property of the global object and if you do that making it an export (as you've done) doesn't seem to have purpose (to me). – Lonnie Best Mar 09 '20 at 18:06
  • 1
    More or less what I ended up doing. – Bondolin Mar 09 '20 at 18:14

1 Answers1

0

I ended up adopting an approach similar to the one here: How do you explicitly set a new property on `window` in TypeScript?

// bundled.ts
import * as Excel from 'exceljs';
import { saveAs } from 'file-saver';

declare const $find: any;

// type configExport as window property
declare global {
    interface Window {
        configExport: any;
    }
}

// add configExport to window global
window.configExport = function() {
    ...
}
Bondolin
  • 2,793
  • 7
  • 34
  • 62