Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export a function with Webpack and use it in an HTML page?

I have a file called index.js:

"use strict";

var $ = require("jquery");
window.jQuery = $;

export function foo() {
    console.log('hello world');
}

And in the same directory, webpack-config.js:

module.exports = {
    entry: './index.js',
    output: {
        filename: './dist.js'
    },
    mode: "development"
};

And finally I have an index.html file which loads my bundled JavaScript, and tries to use the exported function definition...

<script src="/media/js/dist/dist.js"></script>
<script type='text/javascript'>
    foo();
</script>

When I run webpack, I see no output errors.

But when I load my HTML page, I see:

(index):211 Uncaught ReferenceError: foo is not defined
   at (index):211

What am I doing wrong? The dist.js file is loading perfectly OK.

like image 928
Richard Avatar asked May 12 '19 19:05

Richard


1 Answers

Add a library property to your output configuration:

module.exports = {
    entry: './index.js',
    output: {
        filename: './dist.js',
        library: 'myLibrary'
    },
    mode: "development"
};

Then in index.js, you should be able to call foo() like so:

myLibrary.foo();

For this to work it's important that the foo() function is being exported with export function and not export default function

like image 195
AlliterativeAlice Avatar answered Oct 13 '22 00:10

AlliterativeAlice