The original link

CommonJS modules

Module can be either client side or server side, secure or insecure, and can be implemented today or supported by future systems using syntax extensions

The Module context

  • In a module, there is a free variable “require”, which is a function.
    • The require function accepts a module identifier
    • Require returns apis exported by external Modules
    • If there is a dependency loop, it may not have finished executing when a passing dependency of an external Module needs it; In this case, if you want module execution, the object returned by “require” must contain at least the export required by the external module before calling require(causing the current Module to execute).
    • Requie must report an error if a module cannot be exported
  • In a Module, there is a free variable called export, which is an object to which the Module can add an API when it executes
  • Module must use an Exports object as the only method of exporting

The module identifier

  • An identifier is a string of terms separated by a forward slash
    const Square = require("./square.js");
    Copy the code
  • A term must be a camelCase identifier, “.”, or “..” .
  • Module identifiers may not have file extensions like “.js”.
  • Module identifiers can be “relative” or “top-level”. If the first item is ‘.’ or ‘.. ‘ , the module identifier is “relative”
  • Top-level identifiers are resolved from the namespace root of the concept module
  • Relative identifiers are resolved relative to identifiers for modules that write and call “require.”
// math.js
exports.add = function () {
  var sum = 0,
    i = 0,
    args = arguments,
    l = args.length;
  while (i < l) {
    sum += args[i++];
  }
  return sum;
};

// increment.js
var add = require("math").add;
exports.increment = function (val) {
  return add(val, 1);
};

// program.js
var inc = require("increment").increment;
var a = 1;
inc(a); / / 2
Copy the code

ES2015 import

Static import statements are used to import bindings exported by another module. Imported modules run in strict mode regardless of whether strict mode is declared. In browsers, import statements can only be used in tags of scripts that declare type=”module”.

// module-name Specifies the module to be imported. Is usually the relative or absolute pathname of the.js file that contains the target module, and may not include the.js extension
// defaultExport specifies the reference name of the defaultExport interface of the import module.
import defaultExport from "module-name";

// name Specifies the whole alias of the import module object, which will be used as a namespace when referring to the import module.
import * as name from "module-name";

// export, exportN Specifies the name of the export interface of the imported module.
import { export } from "module-name";
import { export1, export2 } from "module-name";

// alias, aliasN will reference the name of the specified import.
import { export as alias } from "module-name";
import { export1 , export2 as alias2 , [...] } from "module-name";

// The entire module is imported only as a side effect (neutral word, no pejorative meaning), but does not import anything in the module (interface)
// This will run the global code in the module without actually importing any values
import '/modules/my-module.js';
Copy the code

In addition, there is a function-like dynamic import() that does not rely on the script tag of type=”module”.

var promise = import("module-name"); // This is a phase 3 proposal.
Copy the code

Insert myModule into the current scope with all interfaces exported from the /modules/my-module.js file

import * as myModule from "/modules/my-module.js";
Copy the code

Accessing the export interface means using the module name (” myModule “in this case) as the namespace. For example, if the module imported above contains an interface doAllTheAmazingThings(), you could call it like this:

myModule.doAllTheAmazingThings();
Copy the code

Dynamic import

The standard import is static, so all imported modules will be compiled as soon as they are loaded. In some scenarios, you can use dynamic imports instead of static imports if you want to import modules conditionally or on demand. Here are some scenarios you might need to dynamically import:

  • When a statically imported module obviously slows down the loading speed of the code and is less likely to be used, it may not be needed immediately
  • When statically imported modules clearly take up a lot of system memory and are less likely to be used
  • When imported modules do not exist at load time, they need to be retrieved asynchronously
  • When importing module specifiers, you need to build them dynamically. (Static imports can only use static specifiers)
  • When an imported module has side effects (side effects, in this case, can be understood as code that runs directly in the module), these side effects are only needed if certain conditions are triggered. (In principle, modules can’t have side effects, but many times you have no control over the contents of the modules you rely on.)

The keyword import can be used to dynamically import modules as if they were functions. Called this way, a Promise is returned

import("/modules/my-module.js").then((module) = > {
  // Do something with the module.
});
// This usage also supports the await keyword
let module = await import("/modules/my-module.js");
Copy the code

Standard import scheme: Will the following code demonstrate how to import from a helper module to assist in handling AJAX JSON requests

// file.js
function getJSON(url, callback) {
  let xhr = new XMLHttpRequest();
  xhr.onload = function () {
    callback(this.responseText);
  };
  xhr.open("GET", url, true);
  xhr.send();
}

export function getUsefulContents(url, callback) {
  getJSON(url, (data) = > callback(JSON.parse(data)));
}

// main.js
import { getUsefulContents } from "/modules/file.js";

getUsefulContents("http://www.example.com".(data) = > {
  doSomethingUseful(data);
});
Copy the code

Dynamic import scheme: This example shows how to load a function module to a page based on user action, in this case by clicking a button and then invoking functions within the module.

const main = document.querySelector("main");
for (const link of document.querySelectorAll("nav > a")) {
  link.addEventListener("click".(e) = > {
    e.preventDefault();

    import("/modules/my-module.js")
      .then((module) = > {
        module.loadPageInto(main);
      })
      .catch((err) = > {
        main.textContent = err.message;
      });
  });
}
Copy the code

@import statement in CSS /sass/ LESS files

@import CSS@ rules, used to import style rules from other style sheets. These rules must be loaded before all other types of rules user agents can avoid retrieving resources for unsupported media types, and authors can specify media-dependent @import rules. These conditions import comma-separated media queries specified after the URI. In the absence of any media queries, the import is unconditional. Specifies that all media have the same effect.

grammar

@import url;
@import url list-of-media-queries;
Copy the code

Url: is an or (en-US) that indicates the location of the resource to be imported. The URL can be an absolute path or a relative path. Note that this URL does not need to specify a file; You can specify only the package name, and the appropriate files will be automatically selected. List-of-media-queries: is a comma-separated list of media query criteria that determines the conditions under which CSS rules introduced through urls should be applied. If the browser does not support any of the media query criteria in the list, the CSS file specified by the URL will not be imported

The sample

@import url("fineprint.css") print;
@import "custom.css";
@import url("chrome://communicator/skin/");
@import "common.css" screen;
@import url("landscape.css") screen and (orientation: landscape);
Copy the code