Reputation: 15664
I have been trying something very simple - export and bundle (and babel transpiling) a function using webpack and then call it in my html page's script tag.
sample.js - which is bundled using webpack
export default function sampleFunctionExported1(){
console.log("sampleFunctionExported1");
}
Webpack config (version = 4.44.1)
module.exports = (env, arguments) => {
entry: {
main: ['./assets/js/sample.js', './assets/css/main.scss'],
entry2: ['./assets/js/entry2.js', './assets/css/entry2.scss']
},
output: {
path: path.join(__dirname, '../public/js'),
filename: '[name].js',
library: 'MyLibrary',
libraryTarget: 'var',
// some additional configs/options that I have tried
// libraryTarget: 'window', // tried with this option, it does not work
// libraryTarget: 'umd', // tried with this option, it does not work
// libraryExport: 'default', // tried with this option, it does not work
}
I though it was as easy as adding the library
and libraryTarget
targets to webpack config and then I should be able to call my function as MyLibrary.sampleFunctionExported1()
.
But when I do MyLibrary
in my browser console, it displays as below and MyLibrary.sampleFunctionExported1()
return ... is not a function
error
I have followed suggestions in many of these questions/answers: answer 1, answer 2, answer 3 and various other blog posts but it does not work for me at all.
So after spending so much time, I am posting it here hoping that someone can help me understand what is wrong.
Edit 1: Here is ithe file generated after webpack bundling: /public/js/sample.js
P.S. - Ignore the entry2.js
file as it's an empty file, I just added it to show my config and because I am not sure if having multiple entry points can cause this issue which I am facing currently.
Upvotes: 3
Views: 1075
Reputation: 78920
Because of how you're exporting:
export default function sampleFunctionExported1(){
console.log("sampleFunctionExported1");
}
...your MyLibrary
variable is going to have the shape:
{
default: function() { ... }
}
If you instead want it to have the shape:
{
sampleFunctionExported1: function() { ... }
}
...you need to do a named export instead of a default export:
export function sampleFunctionExported1() {
console.log("sampleFunctionExported1");
}
Upvotes: 1