Modularity wasn’t an issue from the beginning. When the WWW came out, HTML, JavaScript, and CSS (JS and CSS were all introduced later in netscape browsers) were extremely simple and didn’t require modularity.

The requirement of modularity is a product of scale. As Web Page evolves to Web Application, the logic of browser-side processing becomes more and more complex, and the styles and animations displayed become more and more, the requirements for engineering become higher and higher. This is where the need for modularity arises. Meaning of modularity:

  • Reuse of components to reduce development and maintenance costs
  • Components are developed separately to facilitate division of labor and cooperation
  • Modularity follows standards and facilitates automated dependency management, code optimization, and deployment

JavaScript has long been thought of as a simple scripting language, but that has changed a long time ago, with the latest version of JavaScript being a general-purpose programming language rather than a scripting language. Scripting languages, such as the shell, are not designed to perform complex functions, but to do some automation and do not require modularity. General-purpose programming languages for building complex systems, such as Java, typically have modular implementations.

1. Modular standards

Before ES6, JavaScript didn’t have a native module mechanism. Fortunately, JavaScript is very flexible and there are many ways to write code that can be naturally isolated and modularized:

//define

var  modules  =  {}  

modules.mod1  =  {  

  foo  :  function() {... }, bar :function() {... }... } // Call modules.mod1.foo()Copy the code

On the client side this is basically enough, but the problem remains: you can’t manage dependencies, all the code has to be loaded into memory, and which modules need to be handled manually. Module is the product of engineering, but also the result of natural development, there are a lot of natural attempts. Obviously, modules depend on each other and need to follow certain specifications when writing modules. There are quite a few specifications out there, and I wonder if ES6 will be able to end the free-for-all:

  • AMD
  • CMD
  • closure
  • CommonJS
  • ES6

AMD and CMD are the requireJS and seaJS standards, respectively. Using pure native ES5 syntax means that you can only use closures, and writing and reading are weird. It’s worth pointing out that AngularJS uses a similar approach, so much so that Angular writers decided to use AtScript in AngularJS 2. There are too many front wheels, so they made another one, which is better built and compatible with ES6 TypeScript specifications. Further, look at what AMD looks like:

AMD:

define(['./a'.'./b'].function(a,  b)  {  

  ...

})
Copy the code

Closure is a google-produced front-end tool that provides a range of tools and libraries, and has been used for several of Google’s own projects. Closure Compiler bundles all dependent files together by declaring dependencies between modules, and one of the advantages of closure is that it is highly compressed with ADVANCED (destructive) compression.

// file A goog.provide('module1') com.foo.bar = { ... } // file B goog.require('module1')  

var  a  =  com.foo.bar;
Copy the code

However Closure is not perfect, different files share the same global object, so you have to write A.B.C =… .

CommonJS is the modular standard used by Node.js. Node.js is not only a Server for front-end developers, it is also a perfect development platform. It is great to build Web projects using Grunt/gulp on Node. Node’s modular declaration is similar to Closure’s, but goes one step further by naturally isolating the namespace. The above code could be written using CommonJS’s modularity specification

// file A module.exports = {... } var a = require('./foo/bar')

Copy the code

Browserify enables code that uses the CommonJS modularity specification to run on the client.

2. Static and dynamic loading

Before looking at ES6, let’s look at two ways modules can be loaded:

  • Static loading: Occurs at compile time, packing all required dependencies into a file
  • Dynamic loading: Dependencies are loaded at run time

The AMD standard stands for dynamic loading, while CommonJS stands for static loading. AMD is designed for use in browsers, so it loads asynchronously. NodeJS is run on a server, so synchronous loading is more acceptable, so CommonJS is used. Similarly, if you load statically, use synchronous loading, if you load dynamically you must use asynchronous loading.

So what loading mechanism does ES6 use?

ES6 wants static loading to be simple and declarative, but it doesn’t want to give up dynamic loading. It’s almost impossible to do both at the same time, so ES6 provides two separate methods of loading modules.

2.1 Declaration method

import  {foo}  from module1
Copy the code

2.2 Using the System.import API

System.import('some_module') .then(some_module => { // Use some_module }) .catch(error => { ... }); // Welcome to join the front-end full stack development communication circle to learn communication: 1007317281Copy the code

The syntax for export is similar to CommonJS, except that without module, export is called directly. You can export any function, variable, or object

//expt.js

export function  abc() {} / /exportA namedfunction  

export default  function() {} / /export default function  

export num=123  //exportA numericalexport obj={}  

export  {  obj as  default  };

//import

import expt from  'expt'//default export  

import  {default  as  myModule}  from  'expt'  //rename  

import  {abc,num,obj}  from  'expt'
Copy the code

At present, using precompiled method is obviously better than using dynamic loading, the browser ES6 syntax support is poor, if using dynamic loading ES6, in the browser side will have to do ES6 to ES5 translation work, this is obviously repetitive and inefficient. However, as the browser support for ES6 increases, especially with the implementation of the dynamic loading API, the advantages of dynamic loading will show:

  • For a smoother user experience, dynamic loading can achieve a loading mode similar to LazyLoad, which disperses the download time
  • Simpler projects, no precompilation required, and projects can be configured with many fewer tools
  • The popularity of HTTP/2 tends to use multiple small requests, which are suitable for dynamic loading

Practice 3.

If you are using ES6 now, you can choose the pre-compiled method of dynamically loading the module System.js or Browserify.

Use system.js+ Babel to load dependencies dynamically. System.js is an implementation of ES6 dynamic module loading. Write a small DEMO:

Project initialization

bower install babel system.js  --save
index.html
    <script src="/bower_components/system.js/dist/system.js"></script>

    <script>

      System.config({

          baseURL  :  "/scripts",

          transpiler  :  'babel',

          map  :  {

            babel:'/bower_components/babel/browser.js'}} // Welcome to join the front-end full stack development exchange exchange: 1007317281) system.import ('main.js').then(function(m){

        m.default.sayHello()

      })

    </script>
main.js

export  default  {  

  sayHello  :  function(){

    console.log('hello')}}Copy the code

Precompile using gulp+ Browserify + Babel. Gulp is a task management platform based on node. js. Precompilation is a lot of configuration and tedious, so it is recommended to use Yeoman to generate the skeleton of your project. For example, use generator-ES6-webApp.

The build is very simple and is performed in the project directory

yo es6-webapp
Copy the code

Install dependencies without dependencies.

4. Others, about the trend of front-end

What does ES6 modularity mean?

More powerful front-end, Web technology overall move forward. The growth of HTML5 and the support of some of the best browsers has pushed the web forward as a whole. Previously, things like rendering were done on the back end because browsers were weak and there were old IE laggards.

Simplifying the programming model, manually managing JS dependencies and packaging multiple JS components is eliminated, and with the WebComponents standard, the Web can be developed without using template engines and precompiled engines.

Front-end has further implications — in the past the browser was a tool, now the browser is an important tool, and in the future the browser will be the user’s only operating system.

Thank you for watching, if there are shortcomings, welcome to criticize. 👈👈👈 this time we recommend a free learning group, which covers mobile application website development, CSS, HTML, Webpack, Vue node Angular and interview resources, etc. For students who are interested in web development technology, welcome to join Q group: 👉👉👉1007317281👈 port, no matter you are small white or big, I welcome you, there is a set of efficient learning routes and tutorials organized by Big to share with you for free, while updating video materials every day. In the end, I wish you all success as soon as possible, get satisfactory offer, fast promotion and salary increase, and walk on the peak of life.