Current modular specifications for streams:
Server: CommonJS in Node.js Browser: ES Modules in Browers
ES Modules
The basic features
- Automatically adopt strict mode, ignoring ‘use strict’
- Each ESM module is a separate private scope
- ESM requests external JS modules through CORS
- 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:
- Imports and exports use the fixed ESM syntax
- If the output is a variable, the output is the memory address of the variable, not a copy of the value to the external
- Imported external modules are read-only and cannot be modified