Search code examples
javascriptlaravelwebpacklaravel-mixumd

How to import a JS UMD module with Laravel Mix Webpack


I have a JS plugin with the following structure :

(function(global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
        typeof define === 'function' && define.amd ? define(factory) :
        (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.myPlugin = factory());
}(this, function() {
    'use strict';

    /**/
    const myPlugin = (function(options) {
        const api = {};
        return api;
    });

    return myPlugin ;
}));

I'm trying to load this plugin inside the app.js file created by Laravel mix. To do so, in app.js I have the following :

try {
    window.myPlugin = require('./app/plugins/myplugin.js');
} catch (e) {}

Now, the file is actually imported inside app.js, but when I try to use myPlugin within another JS file, I get the error myPlugin is not a function

const pluginVar = myPlugin(options);
//myPlugin is not a function

If I try to console.log(typeof myPlugin) I get Object.


Solution

  • The solution was pretty simple :

    try {
        require('./app/plugins/myplugin.js');
    } catch (e) {}
    

    I guess because the plugin code was being already assigned to window inside the function(global, factory) iife.