Search code examples
javascriptmoduleamdwebpack-2

Using own modules in webpack 2


At the moment I am trying to understand Webpack and AMD. Here is a simple example I wrote for learning purposes. My question is how I access Model()? This is not working as expected because my browser console gives me a reference error. I want Model to be in a global scope.

webpack.config.js:

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

const config = {
    output : {
        filename : '[name].bundle.js',
        path : 'assets'
    },
    entry : {
        main : ['./entry.js']
    }
};

module.exports = config;

test.html:

<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <script type="text/javascript" src="assets/main.bundle.js" charset="utf-8"></script>
    </body>
</html>

entry.js:

require("./mod1");

test = new Model();
document.write(test.calculate());

mod1.js:

define([] ,function(){
    return function(){
        function Model() {
            var model = this;

            model.test = "bla";

            model.calculate = function(){
                return model.test + 45;
            }
        }
    }
});

Update 1 After some experimenting I found out that returning an object works works for me with a change of entry.js

mod1.js:

define([] ,function(){
    var result = new Object();
    result.Model = function(){
        var model = this;

        model.test = "bla";

        model.calculate = function(){
            return model.test + 45;
        }   
    }

    return result;
});

entry.js:

var mod1 = require("./mod1");

var test = new mod1.Model();
document.write(test.calculate());

At this point there is a new question. What if I want Model to be global accessible?


Solution

  • The Model function is not returned. Try

    define([] ,function(){
        return function(){
            return function Model() {
                ...
            }
        }
    }
    

    Update:

    Also, you need a variable to hold the returned module. Try:

    var mod1 = require("./mod1");
    

    in entry.js, then you should be able to var test = new mod1.Model();

    Update 2:

    Remove the wrapping function in mod1.js, it should look like this:

    define([] ,function(){
       return function Model() {
           var model = this;
    
           model.test = "bla";
    
           model.calculate = function(){
               return model.test + 45;
           }
       }
    });