Exporting a function to the front-end with Webpack

I’m new to webpack and trying to set up a basic implementation.

I have a file script.js with some functions in it

scripts.js

export foo = () => {
   console.log('foo')
}

export bar = () => {
   console.log('bar')
}

And I’m trying to add it to my webpack bundle.js such that I can use these functions in the markup.

webpack.confi.js

const path = require('path')

module.exports = {
    entry: './index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    }
}

My index.js looks like this:

import * as scripts from './scripts.js';

This works in node because if I add console.log(scripts.foo()) to my index.js below the import line, I can observe the console log.

But if I try to call foo() in my markup, I get an undefined error:

Uncaught ReferenceError: foo is not defined

index.html

<script src="./dist/bundle.js"></script>
<script>

    scripts.foo(); // throws undefined error

</script>

What am I missing?

17 thoughts on “Exporting a function to the front-end with Webpack”

Leave a Comment