ES6 modular
What is modular
Goal: Make one .js file (A.js) can reference the code in another .js file (B.js)
Module: Just a file.
Modular specification:
- commonjs specification. Nodejs is the commonjs specification.
- es6 specification. ECMAScript specification.
In nodejs, the modular specification: CommonJS
- Export:
module.exports = '导出的内容'
exports.xxx = '导出的内容'
- Import:
const path = require('path')
The modularity in nodejs is different from the modularity in es6.
ES6 modular
ES6 also provides a modular specification: ES6 modules
- Default import and export
- Export:
export default 导出内容
- Import:
import 变量名 from 'js模块路径'
- Export:
- Import and export on demand
- Export:
export const 成员变量名1 = '导出内容1'
export const 成员变量名2 = '导出内容2'
- Import:
import {成员变量名1} from 'js模块路径'
- Export:
The basic steps
Define module
- Create a .js file, in which, write some variables, functions...
// 创建一个模块
// 如何把es6module/a.js中的fn这个函数给main.js中去使用?
const a = 100
function fn(x,y) {
return x + y
}
Export module
// 创建一个模块
// 如何把es6module/a.js中的fn这个函数给main.js中去使用?
// const a = 100
function fn(x,y) {
return x + y
}
// 导出模块中的fn
export {
fn }
Import module
main.js
import {
fn } from './es6module/a.js'
console.log(fn(100,200)) // 300
Default import and export
module-a.js
// 模块a 默认导出
// 可以导出任何格式的内容:字符串 数字 函数 对象 数组 ...
export default {
name: '模块A',
attr: '属性'
}
main.js
import obj from './module-a'
console.log(obj) // {name: "模块A", attr: "属性"}
Import and export on demand
module-b.js
// 模块B 按需导出
export function fn(x,y) {
return x + y
}
export function fn1(x,y,z) {
return x + y +z
}
export const a = 314
Another way of writing:
function fn(x,y) {
return x + y
}
function fn1(x,y,z) {
return x + y +z
}
const a = 314
export {
fn, fn1, a}
main.js
// 按需导入
import {
a,b} from './module-b'
console.log(a,b)
Whole import
// 按需导入(全部成员导入)
import * as all from './module-b'
console.log(all) // 收集了所有成员的变量(对象)
Coexistence of default export and on-demand export
module-c.js
// 混合导入
// 同时有默认导出和 按需导出
const fn = function(x,y) {
return x + y
}
const a = 100
const fn1 = function(x,y,z) {
return x + y+z
}
// 按需导出
export {
a, fn1
}
// 默认导出
export default {
fn
}
main.js
// 有混合导入
import obj, {
fn1} from './es6module/c.js'
console.log(obj,fn1)
Import and export rename
A name exported in a.js is also this name;
There is also a duplicate name in main.js, so you must change the name:
- Change the name when exporting in a.js
- Change the name when importing in main.js
export {
xxx as 新名字}
import {
xxx as 新名字}
// tool.js
const fn = function(x,y) {
return x + y
}
// 导出重命名
export {
fn as f2}
// index.js
import {
f2 as f1} from "./tool.js"
If there are any shortcomings, please advise, to
be continued, continue to update!
Make progress together!