简体   繁体   中英

Exporting and bundling a function using webpack and calling it inside html script tag

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

PS - 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.

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM