preface

Modularity is just the idea, not the implementation

  • Common JS uses a synchronous approach to module specification
  • AMD uses an asynchronous module definition specification

ES modules feature

  • Default strict mode
  • Each ESM has a private scope
  • ESM requests external JS modules through CORE (corresponding CDN support is required)
  • The ESM script tag delays script execution
<script type="module"></script>
<script type="https://unpkg.com/jequery.min.js"></script>
Copy the code

export

  1. Instead of exporting object literals, we export a fixed form: export {name, age}
  2. A reference address is exported, not the corresponding fixed value
  3. The imported members are read-only members and cannot be modified

import

  1. In native ES Module modules, the extension cannot be omitted, only in index.js require
  2. Links in the CDN can be written directly in IMOPRT. Such as:
import {name} from 'http:// locahost:3000/04-import/module.js'
Copy the code
  1. Only execute a module, do not export the object, load the module does not extract
import {} from './module.js'
import './module.js'
Copy the code
  1. You can get all members at once by *
improt * as mod from './modules.js'
console.log(mod.bar)
Copy the code
  1. Dynamic module loading
// Cannot be introduced as a variable
var modulePath = './module.js'
import { name } from modulePath
console.log(name)

// Import can only appear at the top of the line
if (true) {
    import {name} form './module.js'
}

// Dynamic mode (function)
import(. /module.js).then(function(module) {
    console.log(module)})Copy the code
  1. You can use the shorthand default to export
/ / export
export { name, age }
export default 'default export'

// Import (one of two options), on the left side of the title, to rename the default export variable
import title, { name, age } from './module.js'

import { name, age, default as title } from './module.js'
Copy the code

import & export

You can change import to export. Here’s a scenario:

If a file has a large number of imported files, you can modularize it, split it out, and write an index.js file that contains all the imported files. Then manage it by importing it as index.js

/ / index. Js summary
export {foo, bar} from './module.js'
export {hui, zce} from './common.js'
export {button, avatar} from './button.js'

/ / mini - page. Use vue
import {foo,bar, hui, zce, button, avatar} from  './index.js'
Copy the code

ES Modules and CommonJS in Node environment

  • ESModules can import CommonJS Modules, whereas CommonJS can’t import ESModules
  • CommonJS always exports only one default member
  • Note that import does not deconstruct the exported object