Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

commonJs、amd、cmd、 es6 modules、dynamic import #34

Open
MikeMiller3 opened this issue Nov 21, 2017 · 0 comments
Open

commonJs、amd、cmd、 es6 modules、dynamic import #34

MikeMiller3 opened this issue Nov 21, 2017 · 0 comments

Comments

@MikeMiller3
Copy link
Owner

MikeMiller3 commented Nov 21, 2017

es6 modules

es6模块出现之前,js的唯一全局作用域容易出错,随着app越来越复杂,诸如命名冲突和安全问题,这才诞生了module。

  • import和export不能在函数内使用,只能在最外层作用域使用
  • import的变量、函数和class是只读的,不允许被改变
  • 模块代码自动运行在严格模式之下,无法退出严格模式
  • 定义的变量不会添加到全局作用域,只在模块的顶层范围内
  • this在模块顶层的值为undefined
  • 模块不允许在代码中使用HTML风格的注释
//a.js 使用default,只导出一个
export default 1
// 导入名称随意,不加大括号
import A from 'a.js'
import myA from 'a.js'
import sth from 'a.js'
//a.js,命名导出,可导出多个
export const A = 42
export const B = function(){}

//导入根据名称,且加大括号,可全部导出为一个对象
import {A} from 'a.js'
import {B} from 'a.js'
import * as myObject from 'a.js'
console.log(myObject.A)

When to use the curly braces
Exploring ES6: Modules
Understanding ES6: Modules

dynamic Import

来自stage3,该方法返回一个Promise对象用于在需要时进行导入操作js。
css也可以导入

button.addEventListener('click', event => {
    import('./dialogBox.js')
    .then(dialogBox => {
        dialogBox.open();
    })
    .catch(error => {
        /* Error handling */
    })
});
//使用Promise动态引入多个
Promise.all([
    import('./module1.js'),
    import('./module2.js'),
    import('./module3.js'),
])
.then(([module1, module2, module3]) => {
    ···
});
//配合async和await
async function main() {
    const myModule = await import('./myModule.js');

    const {export1, export2} = await import('./myModule.js');

    const [module1, module2, module3] =
        await Promise.all([
            import('./module1.js'),
            import('./module2.js'),
            import('./module3.js'),
        ]);
}
main();

dynamic import
proposal

@MikeMiller3 MikeMiller3 changed the title commonJs、amd、cmd、 es6 modules commonJs、amd、cmd、 es6 modules、dynamic import Nov 21, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant