Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack export function

I have some js files, and each file is a standonlone function with unique name, And I want to pack all this files in one bundle So I do this code

module.exports = {
    entry: {
        app:[
            './file1.js',
            './file2.js',
            './file3.js',
            './file4.js'
        ],
    },
    output: {
        path: './dist/',
        filename: '[name].bundle.js'
    }
};

that's work and I have my bundle file ".dist/app.bundle.js"

Now I have some js code in the HTML body that need to call functions in the bundle, If I try to call function "functionA" (that is difined in file1.js) I get this message in browser console

Uncaught ReferenceError: functionA is not defined

The question is how can I export my functions from bundle to import it in my HTML code ?

like image 222
Touhami Avatar asked Dec 04 '25 17:12

Touhami


1 Answers

Exporting things from an entry point file does not make them available to the global scope. You have two options - either explicitly add the functions to the window object, like so:

window.functionA = functionA;

Or configure your build to output as a library:

// webpack.config.js - abridged
module.exports = {
    output: {
        library: "myModule",
        libraryTarget: "umd"
    }
};

I don't know how the latter interacts with your entry point being set to an array of files - you may have to make a single entry file (main.js or something) that imports all of the functions and then re-exports them contained in an object, or something like that.

like image 149
Joe Clay Avatar answered Dec 06 '25 08:12

Joe Clay