import 导入
6种:./export/app.js
// import...from... 必须在文件的最顶层,最外层的作用域,
// 路径可以是相对路径【或根目录下的绝对路径,或应完整的url(说明可以引用cdn上的一些文件)】,但不能以字母开头【js会以为是加载第三方插件】
import {name} from './module.js'
import {name} from '/2-2/export/module.js'
import {name} from 'http://localhost:3000/2-2/export/module.js'
console.log(name)
// 只执行某个模块,不提取,多用于加载其他项目中的子模块
import {} from './module.js'
import './module.js' // 简写
// 动态导入(可以放在任意文件中的任意位置)
import('./module.js').then(function(module){
console.log(module)
})
// 导入默认参数
import { name, age, default as title} from './module.js'
import title, { name, age } from './module.js' // 简写
// 导入,提取所有成员
import * as mod from './module.js'
console.log(mod)
// 导入单个默认参数
import default as title from './module.js'
export 导出
./export/module.js
// 导出形式 1,分条导出
// export var name = 'foo module'
var name = 'foo module'
function hello(){
console.log('hello world')
}
class Person{}
// 导出形式 2,集中导出
// export { name, hello, Person}
// 导出形式 3,导出重命名,到引入页面,
// import 也需要用已经重命名的参数名,`import {fooName} from './module.js'`
export {
// name as default, // 作为默认项导出,导入页面需要重命名,`import {default as fooName} from './module.js'`
hello as fooHello,
Person as FooPerson
}
// 导出形式 4,默认导出参数
// import 引入页面 可以自定义为任意变量名(除关键字外) `import abc from './module.js'`
export default name
// 注意
// export 后面跟的 {} 是固定用法,不是字面量对象。
// export default {name,age}, 是字面量对象
// import 后面跟的 {} 是固定用法,不是字面量对象。与 export 是对应的引用关系,是存储空间地址的引用。
// import 导入的成员是一个只读对象,不可在导入文件中修改。
export…from… 导入和导出
./export/component/index.js
import { Avatar } from './avatar.js'
import { default as Button } from './button.js'
./export/components/avatar.js
export var Avatar = 'Avatar Component'
./export/components/button.js
var Button = 'Button Component'
export default Button
兼容
- 模块: browser-es-module-loader
- 用unpkg.com可以查看模块的所有代码
- 举例 browser-es-module-loader