Current modular specifications for streams:

Server: CommonJS in Node.js Browser: ES Modules in Browers

ES Modules

The basic features

  1. Automatically adopt strict mode, ignoring ‘use strict’
  2. Each ESM module is a separate private scope
  3. ESM requests external JS modules through CORS
  4. The ESM script tag delays script execution

Import and export

# ES Modules privatize the block members for external use and should be exported:exportThe exported member is a read-only reference//////////// modules.js //////////// 
var foo = 'FOO'

function say() {
    console.log('say hello');
}

function tips() {
    alert('alert hello')}// Use the export keyword to export modules for external use
// Regular export fixed syntax (not js object literal object syntax)
export { foo, say, tips }  // Use the export keyword to export modules for external use

// Export the rename syntax
export { 
    foo as fooName, 
    say as sayFun,
    tips as tipsAlert
}  

//////////// app.js ////////////

// Import external module syntax: keyword import (not destruct syntax in ES6)
import { fooName, sayFun, tipsAlert } from './modules.js'
console.log(fooName)
sayFun()
tipsAlert()
Copy the code

Note the following when importing and exporting ES Modules members:

  1. Imports and exports use the fixed ESM syntax
  2. If the output is a variable, the output is the memory address of the variable, not a copy of the value to the external
  3. Imported external modules are read-only and cannot be modified