javascript - 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
};
})();
解决方案
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.
推荐阅读
- mongodb - mac导出路径不断重置
- android - Android TextInputEditText,inputType = textPassword,我看不到点
- php - 如果 PHP 中的时间相同,则将总数和设备添加到一个数组中
- mysql - MySQL:基于另一个并不总是具有匹配值的连接表进行排序
- android - 如何为 Launcher3 默认工作区设置最喜欢的应用程序 - Android Source
- css - 将图像放入使用纯 CSS 完成的基本梯形?
- c++ - 将 ProcessEntry32.szExeFile 与用户输入的数据进行比较时,C++ _wcsicmp 代码未编译
- javascript - 你如何让用户在 html 中为 select 标签选择默认值?
- php - 如何在 linux 上的 git hook 中重新启动进程
- sql - 如何从错误消息sql server中查找表名和列名