Module usage in es6

Module usage in es6

  • Keyword importimport module
  • Keyword exportimport module

export

create a new filemj.js

export function plus(a, b) {
    
    
  return a + b
}

import

Import needs to be placed in the script tag of type module

import * as m from './mj.js';

alert(m.plus(1, 2));

Use import() to import the module, the script where import() is located does not need to set the type to module. The
import() function returns a Promise object

import('./mj.js').then(r => {
    
    
  alert(r.plus('hello', 'world'))
})

Complete code

moduleCode

export function plus(a, b) {
    
    
  return a + b
}

htmlCode

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>es6 模块</title>
</head>
<body>

<script type="module">
    import * as m from './mj.js';
    alert(m.plus(1, 2));
</script>
</body>
</html>

Guess you like

Origin blog.csdn.net/BDawn/article/details/114886782