7

Just started using webpack-2 and have a question about global functions. Have these functions in js file named showPictures.js:

function isEmpty(el) {
    var result = !$.trim(el.html());
    return result;
}
function showPicturesList() {
    if (!isEmpty($('#picture-name-list'))) {
        var pictureList = document.getElementById("added-pictures");
        pictureList.style.visibility = 'visible';
    }
}

And I have another file util.js in witch I am calling showPicturesList() function

window.onload = function(){
    showPictureList();
}

Simply using js I would import both scripts into my html, but with webpack I can make one file for both of them so webpack.config.js I added both of these files as entry array. My output file bundle.js looks as it should it has both of those files inside of it. The question is what would be the easiest way with minimal changes on js files to call showPictureList() function from utils.js file?

Lukas Karmanovas
  • 409
  • 1
  • 4
  • 14

1 Answers1

4

You can use ES2015/ES6 modules to import your functions which have been exported in another file. In your showPictures.js file you export the functions you want to expose, by adding the export keyword.

export function showPicturesList() {
    if (!isEmpty($('#picture-name-list'))) {
        var pictureList = document.getElementById("added-pictures");
        pictureList.style.visibility = 'visible';
    }
}

And then you need to import them in your util.js.

import { showPicturesList } from './showPictures';

For detailed informations on how to use modules you can have a look at Exploring JS: Modules.

With this you also don't need to add both files to entry in your webpack config, because webpack will see the imports and include eveything you're importing.

Michael Jungo
  • 31,583
  • 3
  • 91
  • 84
  • And what about using this function in html? Would that work also or not? – Lukas Karmanovas Feb 17 '17 at 19:38
  • 2
    No it doesn't. You would need to expose it either in your webpack config or by defining it on `window`. Look at this question for details: [Calling webpacked code from outside (HTML script tag)](http://stackoverflow.com/questions/34357489/calling-webpacked-code-from-outside-html-script-tag) – Michael Jungo Feb 17 '17 at 19:49