module(JS模块系统)

JS - module(模块系统)

重新学习ES6 倒数第一章 module

什么是module?

百度的解释

之前接触过AngularJS,现在看Dojo,都有对模块的使用。在dojo官网看到这段文字,觉得很好得对JS的模块化的必要性有所解释,所以记录下来:

What is a module?

A module is a value that can be accessed by a single reference. If you have multiple pieces of data or functions that you want to expose in a module, they have to be properties on a single object that represents the module. Practically speaking, it's overkill to create a module for a simple value like var tinyModule = 'simple value';, but it would be valid. Modules start to make a lot more sense for modularizing your code - splitting it up into logical subsets for handling specific functionality. If you want to represent a person with information like name and address, perhaps even add some methods to your person, it starts to make sense to put all that code in a single location. A module is stored in your file system in a single file.

以上意思主要就是:

模块化可被简单接口引用,当你有很多数据和函数(功能)要作为完整个体展示的时候,你可以把他们作为一个module来定义,这些数据和函数(功能)作为独立对象去构Module。Module意义就在于模块化代码,使你的代码分成一个个逻辑上独立的子集,每个子集处理特定的功能。例如,你想定义人,定义中涉及人的属性信息,例如名字、地址。甚至加入一些函数去定义人这个个体。你把定义人的相关代码放在同一个地方更为合理。Module就是存放这样的代码的文件,在整个文件系统中,这个文件是可以被单独调用的。

基本了解

CommonJS 模块

动态加载 执行到了才会加载

let { stat,exists,readFile } = require('fs')

//等同于

let _fs = require('fs')
let stat = _fs.stat;
let exists = _fs.exists;
let readfile = _fs.readfile;

ES6模块

静态导入 页面加载自动引入

import { stat, exists, readFile } from 'fs'

 

 

Module的基本语法

导出 - Math.js

function add(a,b){
   return console.log(a+b);
}
export {add}

导入- demo.js

import {add} from './Math.js'
add(1,2)
//
import {add as aMath} from './Math.js'
aMath(1,2)

 

输出变量写法

//1.
export var firstName = 'Michael'
export var lastName = 'SwalT'
export var year = '1888'
//2.
var firstName = 'Michael'
var lastName = 'SwalT'
var year = '1888'
export{ firstName, lastName, year }
//3.
function v1(){...}
function v2(){...}
function v3(){...}
export {
v1 as streamV1,
v2 as streamV2,
v3 as streamLatestVersion
}
//执行所加载的模块
import 'loading'

模块的整体加载

//除了指定加载某个输出值,还可以使用整体加载, 即用星号(*) 指定一个对象, 所有输出值都加载在这个对象上面
//模块代码
export function area(radius){
   return Math.PI * radius * radius
}
export function circumference(radius){
return 2 * Math.PI * radius
}

//js
import * as circle from './MathModule.s'
console.log('圆面积:' + circle.area(4))
console.log('圆周长:' + circle.circumference(14))

export default

//module 
export default function(){
   console.log('foo')
}
//js
import module from './export-default'
modulr()

 

 

 

 

注意事项:

import export 不可动态处理 !

import 是只读的 本质是输入接口 所以不允许在加载模块的脚本里面, 改写接口

但是如果引入的是一个对象, 那么这个对象的属性值是允许修改的, 但是很难查错

 

等我学完再写

posted @ 2020-09-16 21:11  swalT_link  阅读(758)  评论(0编辑  收藏  举报