模块化module
模块是文件中可重用的代码片段,可以导出然后导入以在另一个文件中使用。模块化程序是其组件可以分离、单独使用和重新组合以创建复杂系统的程序。
es6中的模块导出导入
export/import基本使用
导出变量/函数/类
/*inside module.js*/
export const name='guluji';
export const functionA = ( param ) = >{
}
export class Cat{
constructor(name,age){
this.name=name;
this.age=age;
}
run(){
console.log(this.name+"is running")
}
}
或者导出对象
const name='guluji';
const functionA = ( param ) = >{
...
}
class Cat{
constructor(name,age){
this.name=name;
this.age=age;
}
run(){
console.log(this.name+"is running")
}
}
export {name, functionA, Cat}
导入
//方法1
import { name, functionA, Cat } from '/path/module.js'
//方法2
import * as resouce from '/path/module.js'
console.log( resouce.name);
默认导出/导入
同一个模块中只允许存在一个默认导出
const resources = {
valueA,
valueB
}
export { resources as default };
/*简写*/
export default resources;
导入:
import resources from 'path/module.js';
如果默认导出是个对象,要先导入该对象才能使用
// This will work...
import resources from 'module.js'
const { valueA, valueB } = resources;
// This will not work...
import { valueA, valueB } from 'module.js'
命名冲突
/* inside greeterEspanol.js */
const greet = () => {
console.log('hola');
}
export { greet };
/* inside greeterFrancais.js */
const greet = () => {
console.log('bonjour');
}
export { greet };
在main.js里可以这样:
/* main.js */
import { greet as greetEspanol } from 'greeterEspanol.js';
import { greet as greetFrancais } from 'greeterFrancais.js';
greetEspanol(); // Prints: hola\
greetFrancais(); // Prints: bonjour
CommonJS的导入导出
导出:
module.exports = {
name:'lucy',
functionA( param ){
...
}
导入:
let { name,functionA } = reuire('module');
//等同于
let _m=require('module');
let name=_m.name;
let functionA=_m.functionA;