Search code examples
javascriptwebpackes6-module-loader

Invoke function in webpack module from global scope in script tag


I cannot seem to get my head around this problem:

Think of a simple example app with a javascript module app1.js that in the simplest version looks like this:

function configure() {
   // configure app
}
function start(id) {
   // start app
}

// This is what I dislike and would like to find a better solution!
window.APP = {start: start};

export default {configure};

I have html page app.html that looks like this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <div id="view"></div>
        <script src="app.bundle.js"></script>
        <script>APP.start('view');</script>
    </body>
</html>

and a webpack configuration file webpack.config.js that looks something like this:

const webpack = require('webpack'); const path = require('path');

module.exports = {
  entry: {'app': './app.js'},
  output: {
    path: __dirname,
    filename: '[name].bundle.js'
  },
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel?presets=es2015'
    }]
  }
};

The only way I was able to come up with, is to export the start function to an APP namespace in the window object (window.APP = {start: start}) like this was done in pre-module times. Is there any better (more modular way) to do this?


Solution

  • Do you really need to 'trigger' or 'start' the script from outside of it? Given the pattern you describe above, you can just have your webpack entry point kick things off (e.g. it imports the relevant modules and then uses them).

    If you really do need to load your webpack build as a library of sorts, to be used by other js on the page, you want to look at output.library and output.libraryTarget options in webpack's config. These tell webpack to build your bundle as a library, with libraryTarget specifying how the library is defined at runtime (e.g. the var option defines your library as a variable, which would likely be a global, similar to jQuery).