首页 > 解决方案 > Load a javascript file into a module pattern on Client-side

问题描述

I have a simple javascript module pattern that executes client-side.

var module = (function() {

    var _privateVariable = 10;

    function publicMethod () {

        console.log("public method; private variable: " + _privateVariable);

    }

    return {
        publicMethod: publicMethod
    };

})();

Let's say I want to load in another module (which also uses a module pattern) from a separate javascript file. How do I do that, i.e. something like:

?? Load other module here ??
var _other_module = ??

var module = (function() {

    var _privateVariable = 10;

    function publicMethod () {

        console.log("public method; private variable: " + _privateVariable);

        console.log("public method; other module: " + other_module.publicMethod());
    }

    return {
        publicMethod: publicMethod
    };

})();

标签: javascriptmodule-pattern

解决方案


You can't. To load another module form another file you need to use a Module formats.

It's a long story, i will try to shorten.

Let's talk first about the old way. earlier the developer used to load alle the JS-Files in a certain order in the HTML-Page. If we have 2 JS-Files index.js and variables.js and we want to get a variable from varible.js in index.js, we had load them like that

<script src="variables.js"></script>
<script src="index.js"></script>

But this is not a good way and has many negatives.

The right way is to use a Module formats.

There are many Module formats,

  • Asynchronous Module Definition (AMD)
  • CommonJS
  • Universal Module Definition (UMD)
  • System.register
  • ES6 module format

and each format has own Syntax.

For example CommonJS:

var dep1 = require('./dep1');  

module.exports = function(){  
   // ...
}

but the Browsers dont't understand that. so we need a Module bundlers or Module loaders to convert our code to code which browsers can understand.

Module bundlers: Bundle your inter-dependent Javascript files in the correct order

  • Browserify
  • Webpack

Module loaders: a module loader interprets and loads a module written in a certain module format.

  • RequireJS
  • SystemJS

This article will help you so much to understand exactly how modules work.


推荐阅读