Perhaps the most detailed introduction guide to UMD modules

Posted by m00p4h on Thu, 29 Aug 2019 08:08:07 +0200

Learning UMD

introduce

this Warehouse Recorded some demo s about the specification of javascript UMD module, which is very helpful for me to learn UMD specification, and I hope it can also help you.

review

Several blogs about javascript modules have been written before. The links are as follows:

In recent days, I'm going to summarize the knowledge of javascript module, so I built this module. Git Warehouse If you can help me, please order a star. Thank you very much.

This blog mainly talks about my own understanding and thinking about UMD. From the realization of a simple UMD module to the realization of a dependent UMD module, the whole process deepens my understanding of UMD module.

What is UMD

The so-called UMD (Universal Module Definition) is a general module definition specification for javascript, which enables your modules to play a role in all running environments of javascript.

Implementation of Simple UMD Module

To implement a UMD module, we need to consider the existing mainstream javascript module specifications, such as Common JS, AMD, CMD and so on. So how can these standards be met at the same time?

The first thing to think about is that modules end up exporting an object, function, or variable.

The definition of module export is totally different for different module specifications.

Therefore, we need a transitional mechanism.

First, we need a factory, which is the factory function. It is only responsible for returning what you need to export (objects, functions, variables, etc.).

Let's start by exporting a simple object.

function factory() {
    return {
        name: 'I am one umd Modular'
    }
}

Global Object Mount Properties

Assuming that CommonJS, AMD, CMD are not considered, how should we write this module as an attribute of a global object?

(function(root, factory) {
    console.log('No module environment, mounted directly on global objects')
    root.umdModule = factory();
}(this, function() {
    return {
        name: 'I am one umd Modular'
    }
}))

We write factory as an anonymous function and use IIFE (immediate execution function) to execute the factory function. The returned object is assigned to root.umdModule, where root is the global object, whose value may be window or global, depending on the running environment.

open Links to effect pages If you want to see the source code, click on it. Git Warehouse To observe the file loading order of Network, we can see that the principle is to rely on first.

Further, compatible with AMD specifications

It's also easy to be compatible with AMD. Judge whether the environment meets the AMD specification. If satisfied, the definition function provided by require.js is used to define the module.

(function(root, factory) {
    if (typeof define === 'function' && define.amd) {
        // If there is a definition function in the environment and the definition function has an AMD attribute, it can be judged that the current environment meets the AMD specification.
        console.log('yes AMD Module specifications, such as require.js')
        define(factory)
    } else {
        console.log('No module environment, mounted directly on global objects')
        root.umdModule = factory();
    }
}(this, function() {
    return {
        name: 'I am one umd Modular'
    }
}))

open Links to effect pages As you can see, the principle is that the caller loads first, and the dependent modules are loaded later.

Take-off, Direct UMD

Similarly, it then determines whether the current environment meets the Common JS or CMD specifications, and uses the corresponding module definition method to define the module.

(function(root, factory) {
    if (typeof module === 'object' && typeof module.exports === 'object') {
        console.log('yes commonjs Module specification, nodejs Environmental Science')
        module.exports = factory();
    } else if (typeof define === 'function' && define.amd) {
        console.log('yes AMD Module specifications, such as require.js')
        define(factory())
    } else if (typeof define === 'function' && define.cmd) {
        console.log('yes CMD Module specifications, such as sea.js')
        define(function(require, exports, module) {
            module.exports = factory()
        })
    } else {
        console.log('No module environment, mounted directly on global objects')
        root.umdModule = factory();
    }
}(this, function() {
    return {
        name: 'I am one umd Modular'
    }
}))

Ultimately, using require.js, sea.js, nodejs or global object mounting attributes can perfectly use umd-module.js module to achieve unification.

Give a link to the effect page of calling UMD to sea.js. sea.js calls UMD module

The nodejs call UMD module needs to execute the node command.

node umd-simple-used-by-nodejs

The results are as follows:

Dependent UMD Modules

Of course, we can't stop there. Modules will be called, and of course other modules will be called. So we also need to implement a dependent UMD module to verify the feasibility of UMD specification.

Global Object Mount Properties

This is simple. Introduce the dependent module before your module in html. Both umd-module-dependent and umd-module are UMD modules, and the latter depends on the former.

<!DOCTYPE html>
<html>
    <head>
        <title>Test UMD</title>
        <!-- Dependence comes first -->
        <script src="assets/js/umd-dep/umd-module-depended.js"></script>
        <script src="assets/js/umd-dep/umd-module.js"></script>
        <script src="assets/js/umd-dep/umd-global.js"></script>
    </head>
    <body>
        <h1>test UMD Modular</h1>
        <h2></h2>
        <p id="content"></p>
        <p id="content2"></p>
    </body>
</html>

Point open Links to effect pages See more clearly!

Compatible with AMD specification

We first define the module path in the entry file umd-main-requirejs.js for easy invocation.

require.config({
    baseUrl: "./assets/js/umd-dep/",
    paths: {
        umd: "umd-module",
        depModule: "umd-module-depended"
    }
});

The dependent module umd-module-dependent only needs to simply implement the UMD specification.

The caller umd-module needs some processing. According to the requirement. JS specification, when defining, the dependent module depModule is specified, while the anonymous factory function needs to receive the dependent module depModule on the parameters.

(function(root, factory) {
    if (typeof define === 'function' && define.amd) {
        console.log('yes AMD Module specifications, such as require.js')
        define(['depModule'], factory)
    } else {
        console.log('No module environment, mounted directly on global objects')
        root.umdModule = factory(root.depModule);
    }
}(this, function(depModule) {
    console.log('I called the dependency module', depModule)
    // ... omitted some code, go to the code warehouse and see
    return {
        name: 'I am one of them. umd Modular'
    }
}))

open Links to effect pages See more clearly!

UMD Dependency Writing

Similarly, specifications require you to write modular dependencies as you write them.

(function(root, factory) {
    if (typeof module === 'object' && typeof module.exports === 'object') {
        console.log('yes commonjs Module specification, nodejs Environmental Science')
        var depModule = require('./umd-module-depended')
        module.exports = factory(depModule);
    } else if (typeof define === 'function' && define.amd) {
        console.log('yes AMD Module specifications, such as require.js')
        define(['depModule'], factory)
    } else if (typeof define === 'function' && define.cmd) {
        console.log('yes CMD Module specifications, such as sea.js')
        define(function(require, exports, module) {
            var depModule = require('depModule')
            module.exports = factory(depModule)
        })
    } else {
        console.log('No module environment, mounted directly on global objects')
        root.umdModule = factory(root.depModule);
    }
}(this, function(depModule) {
    console.log('I called the dependency module', depModule)
    // ... omitted some code, go to the code warehouse and see
    return {
        name: 'I am one of them. umd Modular'
    }
}))

Called for sea.js Example links.

The nodejs call is also tested on the command line.

node umd-dep-used-by-nodejs

The results are as follows:

summary

The above implements a simple UMD module, and also verifies the feasibility of UMD modules when there are dependencies between them. Although this article takes simple object export as an example, it is enough to be the starting point for us to go deep into UMD specification.

Finally, I had the cheek to ask for a star. Light me up

Initial link

Scan the following widget 2-D code or search Tusi blog, read the latest article immediately!

Topics: Javascript Programming git Attribute