天天看点

ES6的模块化与CommonJS模块化

ES6模块化

代表:Vue

语法:

导入:import xxx from、import {xxx} from

导出:export、export default

特点:

this指向undefined

编译时输出接口

可以单独加载其中的某个接口(方法)

静态分析,动态引用。输出的是值的引用

  • import命令用于输入其他模块提供的功能;export命令用于规定模块的对外接口。
  • export 可以有多个,export default 仅有一个
//a.js 模块a文件 导出多个方法
export function getCookie(key) {
    ...
}

export function setCookie(key) {
    ...
}

b.js 引入模块并使用
import { getCookie, setCookie } from './a';


//a.js default关键字只导出一个方法或对象
export default {
  info(content) {
    ...
  },
  error(content) {
    ...
  },
};           
/* es6规范 默认暴露
  export{} / export default
  import from
*/

function React(){
  console.log("模拟React方法暴露")
}
React.Component = function(){
  console.log("模拟React上的component方法暴露");
}

const Component = React.Component;
const name = 'dyh分别暴露'
export { Component,name }

export default React;

//es6 模块化 引入
// import React,{Component} from 'react' 模拟
import React,{Component,name} from '../../utils/react'
import { say } from '../../utils/tools';
React();
React.Component();
Component()
console.log(name,11)           

CommonJS模块化

代表:node.js

导入:require()

导出:module.exports、exports

this 指向当前模块

运行时加载。CommonJS脚本代码在require的时候,就会全部执行。一旦出现某个模板被“循环加载”,就只能输出已经执行的部分,还未执行的部分不会输出。

加载的是整个模块,即将所有的接口全部加载进来。

输出的是一个值的拷贝

c.js c模块
const c = ['我是c'];
c.log('c');
export default c;

b.js b模块
Array.prototype.log = function (p) {
    console.log('test>>'+p);
}
const b = ['我是b'];
export default b;

a.js a模块
import bb from './b'; //如果在c模块之前没有使用b模块,c模块中是无法是用原型上扩展的方法的,抛出错误
import cc from './c';
const aa = ['我是a'];
aa.log('a');
bb.log('b');           
/* commonjs规范 暴露
  exports / module.exports 推荐后者
  require()
*/
module.exports = {
  name:'dyh',
  age:100,
  say(){
    console.log('commonjs规范导出1')
  }
}

// commponentjs 模块化 require 使用
let obj = require('../../utils/tools')
console.log(obj,obj.name)
obj.say()
say()           

继续阅读