es6中模块用法

es6中模块用法

  • 关键字import导入模块
  • 关键字export导入模块

export

新建文件mj.js

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

import

import需要放置在type为module的script标签中

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

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

使用import()导入模块,import()所在script不需要设置type为module
import()函数返回一个Promise对象

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

完整代码

module代码

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

html代码

<!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>

猜你喜欢

转载自blog.csdn.net/BDawn/article/details/114886782