2

I have a single exported module in index.js with a function start() that I would like to call in the body tag of my HTML with <body onload='App.start();'>

Here is a similar question whose answer I have tried: Calling webpacked code from outside (HTML script tag)

Here is code from a project doing exactly this: https://github.com/zv/tree <body onload="ZVTree.draw();">

require('babel-polyfill');
var path = require('path');
var dir_js = path.resolve(__dirname, 'src');
var dir_build = path.resolve(__dirname, 'build');

module.exports = {
    entry: path.resolve(dir_js, 'main.js'),
    output: {
        libraryTarget: 'var',
        library: 'ZVTree',
        path: dir_build,
        filename: 'zv-tree.js'
    },
    module: {
        loaders: [
            {
                loader: 'babel-loader',
                test: dir_js,
            }
        ]
    },
    // Create Sourcemaps for the bundle
    devtool: 'source-map',
    devServer: {
        contentBase: dir_build,
    }
}; 

Here is my code, with index.js truncated: index.js:

module.exports = {

  start: function(){
    console.log('hey')
    intializeVariables()
    addListeners()

  }}

index.html:

    <script type='text/javascript' src='dist/bundle.js'></script>
</head>
<body onload = "App.start();">
<div id ='mainContainer'>

webpack.config.js:

module.exports = {
    entry: './index.js',
    output: {
        libraryTarget: 'var',
        library:'App',
        path: './dist',
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            { test: /\.js$/, loader: 'babel', exclude: /node_modules/ }
        ]
    }

}

Everytime I run the project in my browser I get the error: Uncaught ReferenceError: App is not defined when it should be exposed as a library, it also won't run if I put the whole thing in a script tag instead of body. Any help or ideas are greatly appreciated.

Community
  • 1
  • 1
Nohman
  • 65
  • 7
  • I haven't tried your code but I'm curious: Why does `webpack.config.js` set `filename: 'zv-tree.js'` but the script tag loads `dist/bundle.js` ? Are you loading the correct file or a leftover from some earlier experiment? – Peter V. Mørch Jan 13 '17 at 08:38

0 Answers0