Home > Software engineering >  Prevent webpack from removing my exported function
Prevent webpack from removing my exported function

Time:03-30

Im trying to create a Razor Class Library which is exposing 1 js function. My problem is that webpack removes my exported function in final bundle file.

index.js

import * as myLib from "someLib"

export function connect(params) {
    // function logic omitted for clarity
}

And this is how I want to consume the js code

using MyComponent.Common;
using Microsoft.JSInterop;

namespace MyComponent.Services
{
    /// <inheritdoc />
    public class MyService : IMyService
    {
        private readonly Lazy<Task<IJSObjectReference>> _myWrapper;

        public MyService(IJSRuntime jsRuntime)
        {
            _myWrapper = new Lazy<Task<IJSObjectReference>>(() =>
                jsRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/MyComponent/index.bundle.js")
                    .AsTask());
        }

        /// <inheritdoc />
        public async Task Connect(params)
        {
            if (_myWrapper is null)
            {
                throw new InvalidOperationException("Wrapper is not initialized");
            }

            IJSObjectReference module = await _myWrapper.Value;

            await module.InvokeVoidAsync("connect", params);
        }
    }
}

The exception I get is (as expected because there is no connect function exposed in index.bundle.js)

Could not find 'connect' ('connect' was undefined).
Error: Could not find 'connect' ('connect' was undefined).
    at https://localhost:7134/_framework/blazor.webassembly.js:1:328
    at Array.forEach (<anonymous>)
    at a.findFunction (https://localhost:7134/_framework/blazor.webassembly.js:1:296)
    at _ (https://localhost:7134/_framework/blazor.webassembly.js:1:2437)
    at https://localhost:7134/_framework/blazor.webassembly.js:1:3325
    at new Promise (<anonymous>)
    at Object.beginInvokeJSFromDotNet (https://localhost:7134/_framework/blazor.webassembly.js:1:3306)
    at Object.St [as invokeJSFromDotNet] (https://localhost:7134/_framework/blazor.webassembly.js:1:59849)
    at _mono_wasm_invoke_js_blazor (https://localhost:7134/_framework/dotnet.6.0.2-mauipre.1.22102.15.kf8l5pkaed.js:1:194973)
    at wasm://wasm/00970ba6:wasm-function[219]:0x1a129

CodePudding user response:

I just found a way to fix this. At the end of index.js I inserted the following line

window.connect = connect;

This makes webpack not to delete the connect function, however it's still not usable via IJSObjectReference because it expects the function to be exported like export function connect so I inserted another line at the end of final index.bundle.js

export function connect(params) { window.connect(params); }

I also had to disable auto webpack builds on my csproj file since my modifications would be lost after every build and that's it, I was able to use my function just fine after that.

  • Related