Foreword
Regarding modularization, the most direct manifestation is the require and import keywords we write. If you check the relevant information, you will definitely encounter the terms CommonJS, CMD AMD, as well as RequireJS, SeaJS, etc. Strange frame. For example, the official website of SeaJS describes itself this way: "Simple and friendly module definition specification, Sea.js follows the CMD specification. Natural and intuitive code organization, automatic loading of dependencies..."
As a front-end novice, I am honest He looked confused and couldn't understand. According to my usual style, before introducing something, I always have to explain why it is needed.
JavaScript Basics
Students who work on the client side should be familiar with OC's #import "classname", Swift's Module and file modifiers, and Java's import package+class mode. We are accustomed to the pattern that referencing a file refers to a class. However, in a dynamic language like JavaScript, things have changed. For example:
Hello Wrold p>
// index.js
function onPress() {
var p = document.getElementById('hello');
p.innerHTML = 'Hello bestswifter';
}
The <script> tag in HTML can be understood as import, so that the onclick event of the button can call the onPress function defined in index.js. </p>
<p> Suppose as the project develops, we find that the clicked text needs to be dynamically generated and generated by other JS files, then simple index.js will not be able to do the job. We assume that the generated content is defined in the math.js file: </p>
<p>// math.js<br>function add(a, b) {<br>return a + b;<br>}<br> </p>
<p> According to the client’s thinking, the index.js file at this time should be written like this: </p>
<p>// index.js<br>import "math.js"<br> <br>function onPress () {<br>var p = document.getElementById('hello');<br>p.innerHTML = add(1, 2);<br>}<br></p>
<p> Unfortunately, JavaScript does not The import method is not supported, which means that methods in other JS files cannot be referenced in one JS file. The correct solution is to call the add method directly in index.js and reference math.js in index.html:</p>
<p><html><br><head><br><script type ="text/javascript" src="index.js"></script>
Hello Wrold